blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
0161be485ecedd4e17fd86e5049d4ef2bea9191d | liyouzhang/Algos_Interviews | /sum_of_two_values.py | 1,254 | 4.375 | 4 | def find_sum_of_two_one(A, val):
'''
input - array of numbers; val - a number
output - bool
1. native:
- try all combinations of two numbers in array: 2 for loops
- for each, test if == target
'''
#1. naive approach
for a in A:
for b in A:
if b != a:
if a + b == val:
retur... | true |
50b40bb9f10c8abbe769296dea8d895e517ee13e | liyouzhang/Algos_Interviews | /819_most_common_word.py | 2,900 | 4.34375 | 4 | '''
Given a paragraph and a list of banned words, return the most frequent word that is not in the list of banned words. It is guaranteed there is at least one word that isn't banned, and that the answer is unique.
Words in the list of banned words are given in lowercase, and free of punctuation. Words in the paragr... | true |
87ae2f7ef55554516cf8cdce8e1a57837533b3e8 | doraithodla/py101 | /learnpy3/word_freq_2.py | 783 | 4.15625 | 4 | # wordfreq2 - rewrite the wordfreq program to take the text from a file and count the words
def word_freq1(str):
"""
takes a string and calculates the word frequency table
:param str: string input
:return: frequency dictionary
"""
frequency = {}
for word in str.split():
if word in f... | true |
16ba194d28de4bf38a2764f173606bce7cde982b | doraithodla/py101 | /shapes.py | 282 | 4.28125 | 4 | from turtle import forward, right
def shape(sides,length):
for i in range(sides):
forward(length)
right(360/sides)
'''
length = int(input("Length: "))
sides = int(input("Number of sides:"))
'''
for sides in range(3,5):
shape(sides, 100)
| true |
7f7bc72b412846e06bf9b6b5a0c720a4bdc05798 | doraithodla/py101 | /learnpy5/dictionary.py | 2,124 | 4.625 | 5 | # Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)
# Creating a Dictionary
# with Integer Keys
Dict = {1: 'HP', 2: 'compaq', 3: 'dell'}
print("\nDictionary with the use of Integer Keys: ")
print(Dict)
# Creating a Dictionary
# with Mixed keys
Dict = {'Name': 'HP', 1: [1, 2, 3, 4]}
print(... | false |
41b4bb8bda85667c76cc72387e98ef65fc4fd871 | doraithodla/py101 | /learnpy2/wordset.py | 328 | 4.125 | 4 | noise_words = {"if", "and", "or", "the", "add"}
def wordset(string):
"""
converts a list of words to a set
:param list: string input from the user
:return: set object
"""
string_set = set(string.split())
print(string_set)
print(noise_words)
wordset("a is a test to check the test of ... | true |
bea6d8a0680e3c04423bf50c4e89d162cdace2af | eternalseptember/CtCI | /04_trees_and_graphs/01_route_between_nodes/route_between_nodes.py | 1,044 | 4.1875 | 4 | """
Given a directed graph, design an algorithm to find out whether there is
a route between two nodes.
"""
class Node():
def __init__(self, name=None, routes=None):
self.name = name
self.routes = []
if routes is not None:
for item in routes:
self.routes.append(item)
def __str__(self):
list_of_rou... | true |
275a53e865259a0d15f82cdacdc2a58a641b9343 | eternalseptember/CtCI | /07_object-oriented_design/11_file_system/file_system.py | 2,226 | 4.28125 | 4 | """
Explain the data structures and algorithms that you would use to design an
in-memory file system. Illustrate with an example in code where possible.
"""
# What is the relationship between files and directories?
class Entry():
def __init__(self, name, parent_dir):
self.name = name
self.parent_dir = parent_di... | true |
005103cb3b2736711e6dd9a194a19cb0db8bd420 | jcs-lambda/cs-module-project-algorithms | /sliding_window_max/sliding_window_max.py | 1,016 | 4.34375 | 4 | '''
Input: a List of integers as well as an integer `k` representing the size of the sliding window
Returns: a List of integers
'''
def sliding_window_max(nums, k):
# initialize first window and max
window = nums[:k]
current_max = max(window)
maxes = [current_max]
# slide window
for x in nums... | true |
9a40b9d9bee4f82ba28a3f9d2124440df6cf9ab7 | DAGG3R09/coriolis_training | /assignments/Q10_overlapping.py | 318 | 4.125 | 4 |
def is_overlapping (l1, l2):
for le1 in l1:
for le2 in l2:
if le1 == le2:
return True
return False
if __name__ == "__main__":
l1 = [1, 2, 3, 4, 5]
l2 = [5, 6, 7, 8, 9]
l3 = [6, 7, 8, 9, 10]
print(is_overlapping(l1, l2))
print(is_overlapping(l1, l3)) | false |
f01f3cb9fdf5bd6c4167da2ff209ec7df0308681 | subashchandarA/Python-Lab-Pgms-GE8151- | /11MostFrequentWord.py | 660 | 4.34375 | 4 | #Most Frequent word in a string
#str="is program is to find the of the word in the string"
filename=input("Enter the file name to find the most frequent word: ")
fo=open(filename,'r')
str=fo.read()
print("The given string is :",str)
wordlist = str.split(" ")
d={}
for s in wordlist:
if( s in d.keys(... | true |
5dac50e3ef0821386d271fe18a353c279e69ea1e | subashchandarA/Python-Lab-Pgms-GE8151- | /6.1 selecion sort(python method).py | 1,356 | 4.21875 | 4 | def selectionsort(lt):
"select the min value and insert into its position"
for i in range(len(lt)-1):
#min_pos=x
#for x in range(i+1,len(lt)):
# if(lt[min_pos]>lt[x]):
# min_pos=x
min_pos=lt[i:].index(min(lt[i:])) # FIND THE INDEX OF M... | true |
773762755424c84ef55b4218da57e14bfcdaf07a | kevinpalacio/AprendiendoPython | /Aleatorio.py.py | 1,010 | 4.21875 | 4 | # Autor : Kevin Oswaldo Palacios Jimenez
# Fecha de creacion: 16/09/19
# Python tendra varios modulos(module), estos modulos son
# librerias que tiene python
# Se necesita in modulo para un programa,
# import, es la primera instruccion que debera estan presente
# en la consola
import random
# Definimo... | false |
a7cd794a1ef6fc543980181f1cf7144b6dd6639f | ShreyaPriyanil/Sorting-in-Python | /insertionsort.py | 514 | 4.21875 | 4 | def insertionSort(alist):
for index in range(1,len(alist)):
print("TRAVERSAL #: ",index)
position = index
while position>0 and alist[position-1]>alist[position]:
temp = alist[position]
alist[position] = alist[position-1]
alist[position-1] = temp
... | true |
df1eb693316cd623603e43fbee56746b8445b821 | shivdazed/Python-Projects- | /Exceptionhandling.py | 324 | 4.15625 | 4 | try:
a = int(input("Enter the number A:"))
b = int(input("Enter the number B:"))
c = a/b
print(c)
#except Exception as e:
# print(e)
except ZeroDivisionError:
print("We can't divide by zero")
except ValueError:
print("Your entered value is wrong")
finally:
print("Sum = ",a+... | true |
8b886230b5e8b749480f899bac95868e99d0c48b | shivdazed/Python-Projects- | /Calci.py | 553 | 4.28125 | 4 | print("Enter two numbers into the calci\n")
n1 = int(input("Enter the first number---"))
n2 = int(input("Enter the second number---"))
o = input("Choose operator--\n'+'~Addition \n'-'~Subtraction\n'*'~Multiplication\n'/'~Division\n")
if o == '+':
print(f"The sum of {n1} and {n2} ={n1+n2}")
elif o == '-'... | false |
08e7e22f6f39a02caca937e0fca7982fb33c901c | Poonam-Singh-Bagh/python-question | /Loop/multiplication.py | 228 | 4.21875 | 4 | ''' Q.3 Write a program to print Multiplication of two numbers
without using multiplication operator.'''
i = 1
a = int(input("enter a no."))
b = int(input("enter a no."))
c = 0
while i <= b:
c = c + a
i = i + 1
print (c) | true |
13cd95427f9fed8977a2b5de25abae5c22d361c6 | ONJoseph/Python_exercises | /index game.py | 1,013 | 4.375 | 4 | import random
def main():
# 1. Understand how to create a list and add values
# A list is an ordered collection of values
names = ['Julie', 'Mehran', 'Simba', 'Ayesha']
names.append('Karel')
# 2. Understand how to loop over a list
# This prints the list to the screen one value at a time
fo... | true |
ca67ed3630bf2bf15468aaacd138312cb1854ad8 | shubhamjha25/FunWithPython | /coin_flipping_game/coinflipgame.py | 635 | 4.21875 | 4 | import random
import time
print("-------------------------- COIN FLIPPING GAME -----------------------------")
choice = input("Make your choice~ (heads or tails): ")
number = random.randint(1,2)
if number == 1:
result = "heads"
elif number == 2:
result = "tails"
print("-------------------------------- DECIDING ... | true |
d1cee333a1147bc53c0040e732128b8a5d05abca | Anisha7/Tweet-Generator | /tasks1-5/rearrange.py | 1,612 | 4.28125 | 4 | # build a script that randomly rearranges a set of words provided as command-line arguments to the script.
import sys
import random
# shuffles given list of words
def rearrange(args):
result = []
while (len(args) > 0) :
i = random.randint(0, len(args)-1)
result.append(args.pop(i))
ret... | true |
bb8749c3abda670d006b2184f7b620449bb54f07 | joseramirez270/pfl | /Assignment4/generate_model.py | 1,180 | 4.1875 | 4 | """modify this by generating the most likely next word based on two previous words rather than one. Demonstrate how it works with a corresponding conditional frequency distribution"""
import nltk
"""essentially, this function takes a conditional frequency distribution of bigrams and a word and makes a sentence.
... | true |
0a93e0ded92ef09809aa22bd801667587171f6ed | jyoung2119/Class | /Class/demo_labs/PythonStuff/5_10_19Projects/dateClass.py | 1,918 | 4.15625 | 4 | #Class practice
class Date:
def __init__(self, m, d):
self.__month = m
self.__day = d
#Returns the date's day
def get_day(self):
return self.__day
#Returns the date's month
def get_month(self):
return self.__month
#Returns number of days in ... | true |
ac1971b1544ccb491d9ed862258cc4bf3dbccae2 | inbsarda/Ccoder | /Python_codes/linked_list.py | 2,030 | 4.1875 | 4 | ###################################################
#
# Linked List
#
###################################################
class node:
def __init__(self, data):
self.data = data
self.next = None
def insertAtBegining(head,data):
'''
Insert node at begining
'''
newnode = node(data)
... | true |
a4c58d8162dbb4317ec0cfced87e8e3c71860f74 | inbsarda/Ccoder | /Python_codes/reverse_list.py | 1,161 | 4.3125 | 4 | ##################################################################
#
# Reverse the linked list
#
##################################################################
class node:
def __init__(self, data):
self.data = data
self.next = None
class linkedlist:
def __init__(self):
self.head =... | true |
a1593b01f3f3c09d1c392c63612e81506d90243a | doritger/she-codes-git-course-1 | /ex2.py | 1,049 | 4.28125 | 4 | from datetime import datetime
# imports current date and time
def details():
first_name = input("Please enter your first name: ")
surname = input("Please enter your surname: ")
birth_year = input("Please enter the year of your birth: ")
# asks the user to enter name, surname and year of birth
print... | true |
57044de69024d956548f000f130d1afe3b48e66a | Raiane-nepomuceno/Python | /Parte 1/Lista 01/011.py | 501 | 4.25 | 4 | n= int(input('Digite o número:'))
if n%2== 0 and n%5 == 0 and n%10 == 0:
print('O número {} é divisível por:2,5,10'.format(n))
elif n%2!= 0 and n%5 == 0 and n%10 == 0:
print('O número {} é divisível por 5 e 10'.format(n))
elif n%2!= 0 and n%5 == 0 and n%10 != 0:
print('O número {} é divisível apenas por 5'.... | false |
7d315d98c3d2b268a600eee898b046512c0a42df | Raiane-nepomuceno/Python | /Parte 2/EXERCÍCIOS DE LISTAS/004.py | 600 | 4.15625 | 4 | #Crie um programa que leia
#Inicialmente uma sequencia de
#N números inteiros
#e mostre ao final 2 listas: uma sem repetição e outra dos elementos repetidos
op = 1
lista_rep = []
lista3 = []
while op == 1:
op = int(input('Deseja adicionar o elemento [1-sim/2-não]:'))
if op == 1:
n = int(input('Num:'... | false |
59c1517b2ad8cfac4d186e417859ae5dbd190575 | pythoncoder999/Python | /AutomateTheBoringStuff/myPets.py | 272 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Oct 27 01:06:29 2019
@author: Gunardi Saputra
"""
myPets = ["One", "Two", "Three"]
print("Enter a pet name: ")
name = input()
if name not in myPets:
print("I do not have a pet named " + name)
else:
print(name + " is my pet.")
| false |
5fe884067f7af8df12f114e84a40953cab414d6e | abby-does-code/youtube_practice_intmd | /dictionaries!!.py | 2,766 | 4.3125 | 4 | # START
## Keep chugging away bb!
# Dictionary: data type that is unordered and mutable
##Consists of key:value pairs; maps value to associated pair
# Create a dictionary(30:00)
mydict = {"name": "Max", "age": 28, "city": "New York"}
print(mydict)
# Dict method for creation
# mydict2 = dict(name = "Mary", age = 27, ... | true |
a6e6b869f5de7d169dc668b4967332bea5498ae1 | shanbumin/py-hundred | /Day01-15/Day12/demo01/main.py | 1,103 | 4.4375 | 4 | # 字符串常用操作
print('My brother\'s name is \'007\'') # 转义字符
print(r'My brother\'s name is \'007\'') # 原始字符串
# -------------------------------------------------------
str = 'hello123world'
print('he' in str) #True
print('her' in str) #False
print(str.isalpha()) # 字符串是否只包含字母 False
print(str.isalnum()) # 字符串是否只包含字母和数字 True... | false |
18f75cc839f336f3a2f815a578eb5871ad2a7f5c | pranabsg/python-dsa | /get_fibonacci.py | 381 | 4.28125 | 4 | """Implement a function recursively to get the desired
Fibonacci sequence value.
"""
def get_fib(position: int) -> int:
if position == 0 or position == 1:
return position
return get_fib(position - 1) + get_fib(position - 2)
def main():
# Test cases
print(get_fib(2))
print(get_fib(11))
... | true |
f78a79c275e90a90394269b230cdef39dbc4d979 | danecashion/python_example_programs | /first_largest.py | 284 | 4.5625 | 5 | """
Python program to find the largest element and its location.
"""
def largest_element(a):
""" Return the largest element of a sequence a.
"""
return None
if __name__ == "__main__":
a = [1,2,3,2,1]
print("Largest element is {:}".format(largest_element(a)))
| true |
ba9c31ebc3df8d7c0379d0face66c3e4dfecd9e1 | deepdc19/Practice_Problems | /piToNth_chudnovsky.py | 1,006 | 4.1875 | 4 | from decimal import Decimal
from decimal import getcontext
def factorial(n):
'''
Factorial function to find the factorial of the functions
https://en.wikipedia.org/wiki/Factorial
'''
if n < 1:
return 1
else:
return n * factorial(n-1)
def piToNth(num):
'''
chudnovs... | false |
8bf8929bbfe763af15cf61cdb294ca78b59bc057 | annamwebley/PokerHand | /deck.py | 2,626 | 4.15625 | 4 | # Project 3b
# Anna Markiewicz
# May 12
# deck.py
# Shuffle the Card objects in the deck
import random
from card import Card
class Deck:
"""Card Deck, which takes self as input, and creates a deck of cards
"""
def __init__(self):
self.cards = [ ]
for suit in ['C', 'D', 'H', 'S']:
... | true |
492eddbeffe120a0ca71fc4767ce8e6523b04978 | lshpaner/python-datascience-cornell | /Analyzing and Visualizing Data with Python/Importing and Preparing Data/LoadDataset.py | 2,531 | 4.125 | 4 | #!/usr/bin/env python
# coding: utf-8
# ## Analyzing the World Happiness Data
#
#
# ### Preparing the data for analysis
# In this exercise, we will do some initial data imports and preprocessing to get the data ready for further analysis. We will repeat these same basic steps in subsequent exercises. Begin by exe... | true |
28b512c74e3fd196b8ca592e9c81d72bfe1f9672 | lshpaner/python-datascience-cornell | /Constructing Expressions in Python/Computing the Average (Mean) of a List of Numbers/exercise3.py | 975 | 4.53125 | 5 | """
Computing the Average (Mean) of a List of Numbers
Author: Leon Shpaner
Date: July 19, 2020
In exercise3.py in the code editor window, create a new list containing a
mixture of letters and numbers: my_other_list = [1, 2.3, 'a', 4.7, 'd'], and
write an expression computing its average value using a similar expre... | true |
98269365703f82e15da200949483316583454b29 | lshpaner/python-datascience-cornell | /Writing Custom Python Functions, Classes, and Workflows/Simple Ciphers With Lists and Dictionaries/exercise.py | 2,492 | 4.59375 | 5 | """
Simple Ciphers With Lists and Dictionaries
Author: Leon Shpaner
Date: August 14, 2020
"""
# Examine the starter code in the editor window.
# We first define a character string named letters which includes all the
# upper-case and lower-case letters in the Roman alphabet.
# We then create a dictionary (using a ... | true |
060467da007c90e930786d0e4cb38b8cb52940e5 | eyjolfurben/Assignment5 | /Fair traffic lights.py | 1,316 | 4.28125 | 4 | north_int = int(input("Number of cars travelling north: "))
south_int = int(input("Number of cars travelling south: "))
east_int = int(input("Number of cars travelling east: "))
west_int = int(input("Number of cars travelling west: "))
sum_of_all_cars = north_int + south_int + east_int + west_int
north_counter = nort... | false |
bcdb572bcbba2ed318e0d0d9121285be989d6621 | lastcanti/effectivePython | /item3helperFuncs.py | 848 | 4.4375 | 4 | # -----****minimal Python 3 effective usage guide****-----
# bytes, string, and unicode differences
# always converts to str
def to_str(bytes_or_str):
if isinstance(bytes_or_str, bytes):
value = bytes_or_str.decode('utf-8')
else:
value = bytes_or_str
return value
# always converts to bytes... | true |
dca014bef7c07c1f91b5d666afeb53f930ff0892 | shobnaren/python-codes | /Sorting Algorithms/Bubble_sort.py | 391 | 4.21875 | 4 |
def Bubble_sort(arr):
for k in range(0,len(arr)-2):
for i in range(0,len(arr)-k-1):
if arr[i+1] < arr[i]:
temp = arr[i+1]
arr[i+1]=arr[i]
arr[i]=temp
print(arr)
print("Sorted array using Buble sort:",arr)
if __name__ == '__ma... | false |
6e27535bde7a1978b86b9d03381e72a745af83ed | VladislavRazoronov/Ingredient-optimiser | /examples/abstract_type.py | 1,520 | 4.28125 | 4 | class AbstractFood:
"""
Abstract type for food
"""
def __getitem__(self, value_name):
if f'_{value_name}' in self.__dir__():
return self.__getattribute__(f'_{value_name}')
else:
raise KeyError('Argument does not exist')
def __setitem__(self, value_name, ... | true |
d30b39de24b1a1692b5c27899af47a1a73b1d1e5 | Confucius-hui/LeetCode | /从排序数组中删除重复项.py | 1,180 | 4.1875 | 4 | '''
给定数组 nums = [1,1,2],
函数应该返回新的长度 2, 并且原数组 nums 的前两个元素被修改为 1, 2。
你不需要考虑数组中超出新长度后面的元素。
'''
class Solution:
def removerDuplicates(self,nums):
'''
:param nums: list[int]
:return: int
'''
i = 0
while i<len(nums)-1:
if nums[i] == nums[i+1]:
... | false |
498efd52ff80b4f7defd7b9fa0ca851e79ea39b7 | Confucius-hui/LeetCode | /排序算法/Sort.py | 1,873 | 4.15625 | 4 | ##快速排序、冒泡排序、归并排序
class Sort:
def Quicksort(self,nums,start,end):
if start<end:
i = start
j = end
x = nums[start]
while i<j:
while i<j and nums[j]>x:
j-=1
if i<j:
nums[i] = nums[j]
... | false |
e4cf60bedc9df20bb65fdec96560b95f4d05d655 | hankangbok/almanacautomation | /FindDaylightSavingsDates.py | 933 | 4.21875 | 4 | import calendar
def findDSTforYear(year):
Sundaycounter=0
#To find the 2nd Sunday in march for a given year
for i in range(1,15):
ScndSundayCheck=calendar.weekday(year, 3, i)
if ScndSundayCheck==0:
Sundaycounter+=1
if Sundaycounter==2:
DSTStart=[year,3,i]
arrayStart=''.join(str(DSTStart))
... | false |
f9956ce992ed0d0d7024a5829af2f6c4a05cfbff | andywakefield97/Sparta_Training | /Day_6.py | 2,526 | 4.25 | 4 | # class Students:
#
# def __init__(self, name, age, gender):
# self.name = name
# self.age = age
# self.gender = gender
#
# def year(self):
# if self.age == '14':
# return '{} is in Year 7'.format(self.name)
# elif self.age == '12':
# return '{} is... | false |
6c291c935764c099d5c861d070780800d69d965d | HOL-BilalELJAMAL/holbertonschool-python | /0x0B-python-inheritance/11-square.py | 1,102 | 4.28125 | 4 | #!/usr/bin/python3
"""
11-square.py
Module that defines a class called Square that inherits from
class Rectangle and returns its size
Including a method to calculate the Square's area
Including __str__ method to represent the Square
"""
Rectangle = __import__('9-rectangle').Rectangle
class Square... | true |
da4284aa2521689c430d51e0c275b40f2f86348d | HOL-BilalELJAMAL/holbertonschool-python | /0x0C-python-input_output/0-read_file.py | 393 | 4.125 | 4 | #!/usr/bin/python3
"""
0-read_file.py
Module that defines a function called read_file that reads
a text file (UTF8) and prints it to stdout
"""
def read_file(filename=""):
"""
Function that reads a text file and prints it to stdout
Args:
filename (file): File name
"""
with ope... | true |
0bbcccf7cb91667ab15a317c53ac951c900d93a6 | HOL-BilalELJAMAL/holbertonschool-python | /0x0B-python-inheritance/10-square.py | 819 | 4.28125 | 4 | #!/usr/bin/python3
"""
10-square.py
Module that defines a class called Square that inherits from
class Rectangle and returns its size
Including a method to calculate the Square's area
"""
Rectangle = __import__('9-rectangle').Rectangle
class Square(Rectangle):
"""
Represents a class called Re... | true |
adee2a41e59f94a940f45ebbf8fddb16582614a6 | sonsus/LearningPython | /pywork2016/arithmetics_classEx1018.py | 1,334 | 4.15625 | 4 | #Four arithmetics
class Arithmetics:
a=0
b=0
#without __init__, initialization works as declared above
def __init__(self,dat1=0,dat2=0):
a=dat1
b=dat2
return None
def set_data(self,dat1,dat2):
self.a=dat1
self.b=dat2
retur... | true |
aa226fc06796e2e12132527b270f9671bd66bb55 | annabalan/python-challenges | /Practice-Python/ex-01.py | 489 | 4.25 | 4 | #Create a program that asks the user to enter their name and their age. Print out a message addressed to them that tells them the year that they will turn 100 years old.
def aging():
name = input("Enter your name: ")
age = int(input("Enter your age: "))
number = int(input("Enter a number: "))
year = st... | true |
bc917efa9ab9aef3260e21326d9c10c7f51cbc0e | strawhatasif/python | /calculate_average_rainfall.py | 2,396 | 4.5 | 4 | # This program calculates and displays average rainfall based on rainfall amounts per month entered by the user.
# constant for number of months in a year
NUMBER_OF_MONTHS_IN_YEAR = 12
# stores the number of years entered by the user
number_of_years = int((input('Please enter the number of years: ')))
# if the initi... | true |
e6c7ddd18304dd9cb6fadb4d98058483494c0300 | strawhatasif/python | /commission_earned_for_investor.py | 2,983 | 4.34375 | 4 | # This program tracks the purchase and sale of stock based on investor input.
# constant percentage for how much commission an investor earns.
COMMISSION_RATE = 0.03
# PURCHASE OF STOCK SECTION
# Stores the name of the investor when entered.
investor_name = input('What is your name? ')
# Stores the number of shares ... | true |
6fc6becc03fbd9d920f80033889746e04d5852ed | justintuduong/CodingDojo-Python | /Python/intro_to_data_structures/singly_linked_lists.py | 1,957 | 4.125 | 4 |
class SLNode:
def __init__ (self,val):
self.value = val
self.next = None
class SList:
def __init__ (self):
self.head = None
def add_to_front(self,val):
new_node = SLNode(val)
current_head = self.head #save the current head in a variable
new_node.next = c... | true |
5457e1f66077f12627fd08b2660669b21c3f34d3 | AmonBrollo/Cone-Volume-Calculater | /cone_volume.py | 813 | 4.28125 | 4 | #file name: cone_volume.py
#author: Amon Brollo
"""Compute and print the volume of a right circular cone."""
import math
def main():
# Get the radius and height of the cone from the user.
radius = float(input("Please enter the radius of the cone: "))
height = float(input("Please enter the height of the ... | true |
e93a9c53e043b7c1689f8c5c89b6365708153861 | diamondhojo/Python-Scripts | /More or Less.py | 928 | 4.21875 | 4 | #Enter min and max values, try to guess if the second number is greater than, equal to, or less than the first number
import random
import time
min = int(input("Enter your minimum number: "))
max = int(input("Enter your maximum number: "))
first = random.randint(min,max)
second = random.randint(min,max)
print ("The... | true |
01d4ea985f057d18b978cdb28e8f8d17eac02a6d | matthew-kearney/cs-module-project-recursive-sorting | /src/sorting/sorting.py | 1,938 | 4.28125 | 4 | # TO-DO: complete the helper function below to merge 2 sorted arrays
def merge(arrA, arrB):
elements = len(arrA) + len(arrB)
merged_arr = [0] * elements
# Your code here
index_a = 0
index_b = 0
# Iterate through all indices in merged array
for i in range(elements):
# Make sure that... | true |
00b7d2b18548c195bedf516c25a3eda1f4a169ed | Joewash1/password | /Password2-2.py | 596 | 4.21875 | 4 | s=input("please enter your password :: ")
Password = str( 'as1987Jantu35*^ft$TTTdyuHi28Mary')
if (s == Password):
print("You have successfully entered the correct password")
while (s != Password):
print("Hint:1 The length of your password is 32 characters")
s=input("please enter your password :: ")
if(... | true |
bdb4ad158aeda38ada8f2ca88850aab3338393b4 | elrosale/git-intro | /intro-python/part1/hands_on_exercise.py | 1,140 | 4.3125 | 4 | """Intro to Python - Part 1 - Hands-On Exercise."""
import math
import random
# TODO: Write a print statement that displays both the type and value of `pi`
pi = math.pi
print(type(pi), (pi))
# TODO: Write a conditional to print out if `i` is less than or greater than 50
i = random.randint(0, 100)
if i < 50:
... | true |
277001f219bf21982133779920f98e4b77ca9ec0 | DeLucasso/WePython | /100 days of Python/Day3_Leap_Year.py | 465 | 4.3125 | 4 | year = int(input("Which year do you want to check? "))
# A Leap Year must be divisible by four. But Leap Years don't happen every four years … there is an exception.
#If the year is also divisible by 100, it is not a Leap Year unless it is also divisible by 400.
if year % 4 == 0:
if year % 100 == 0:
if year % 4... | true |
435f96309f8dbcc0ebf5de61390aae7f06d4d7e9 | ashwin1321/Python-Basics | /exercise2.py | 1,541 | 4.34375 | 4 | ##### FAULTY CALCULATOR #####
def calculetor():
print("\nWellcome to Calc:")
operation = input('''
Please type in the math operation you would like to complete:
+ for addition
- for subtraction
* for multiplication
/ for division
** for power
% for modulo
Enter... | true |
1b022a05c38b11750eeb5bc824ea2968628533a5 | ashwin1321/Python-Basics | /lists and its function.py | 1,724 | 4.625 | 5 |
########## LISTS #######
# list is mutable, we can replace the items in the lists
'''
grocery = [ 'harpic', ' vim bar', 'deodrant', 'bhindi',54] # we can include stirng and integer together in a list
print(grocery)
print(grocery[2])
'''
'''
numbers = [12,4,55,16,7] # list can also be... | true |
53b0a04657a620aaaf20bfee9f8a5b8e9b08e322 | ashwin1321/Python-Basics | /oops10.public, protected and private.py | 1,231 | 4.125 | 4 | class Employee:
no_of_leaves = 8 # This is a public variable having access for everybody inside a class
var = 8
_protec = 9 # we write a protected variable by writing "_" before a variable name. Its accessi... | true |
0209c76a48557122b10eaedbac5667641078a631 | jvansch1/Data-Science-Class | /NumPy/conditional_selection.py | 292 | 4.125 | 4 | import numpy as np
arr = np.arange(0,11)
# see which elements are greater than 5
bool_array = arr > 5
#use returned array of booleans to select elements from original array
print(arr[bool_array])
#shorthand
print(arr[arr > 5])
arr_2d = np.arange(50).reshape(5,10)
print(arr_2d[2:, 6:)
| true |
dc914377bfebde9b6f5a4e2b942897d4cd2a8e25 | lilimehedyn/Small-projects | /dictionary_practice.py | 1,082 | 4.125 | 4 | #create a dict
study_hard = {'course': 'PythonDev', 'period': 'The first month', 'topics': ['Linux', 'Git', 'Databases','Tests', 'OOP'] }
# add new item
study_hard['tasks'] = ['homework', 'practice online on w3resourse', 'read about generators', 'pull requests',
'peer-review', 'status', 'feedbac... | true |
97dce44d9bdd9dfad2fd37f8e79d5956f6c64bd0 | Vagacoder/LeetCode | /Python/DynamicProgram/Q0122_BestTimeBuySellStock2.py | 2,454 | 4.15625 | 4 | #
# * 122. Best Time to Buy and Sell Stock II
# * Easy
# * Say you have an array prices for which the ith element is the price of a given
# * stock on day i.
# * Design an algorithm to find the maximum profit. You may complete as many
# * transactions as you like (i.e., buy one and sell one share of the stock multi... | true |
6396751b5e099078737ff179113ceda89fbce28c | dishashetty5/Python-for-Everybody-Functions | /chap4 7.py | 743 | 4.40625 | 4 | """Rewrite the grade program from the previous chapter using
a function called computegrade that takes a score as its parameter and
returns a grade as a string.
Score Grade
>= 0.9 A
>= 0.8 B
>= 0.7 C
>= 0.6 D
< 0.6 F"""
score=float(input("enter the score:"))
def computegrade(score):
try:
if(scor... | true |
08de98547c3bd1f48944e321e9abaece43563aa9 | nurur/GeneralProgramming | /TernaryOperator.py | 265 | 4.28125 | 4 | # Ternary Operator in Python
# Rule: a if testCondition else b
x=1; y=2; z=4
print 'x, y, z values are ', x, y, z
print ' '
m = x if (x<y) else z
print 'Ternary operator result:', m
n = x if (x>y) else z
print 'Ternary operator result:', n
| false |
dfe1b71f4bca7dc0438ae83fd418ad131fb8aba9 | huzaifahshamim/coding-practice-problems | /Lists, Arrays, and Strings Problems/1.3-URLify.py | 1,061 | 4.1875 | 4 | """
Write a method to replace all spaces in a string with '%20'. You may assume that the string
has sufficient space at the end to hold the additional characters, and that you are given the "true"
length of the string. (Note: if implementing in Java, please use a character array so that you can
perform this operation i... | true |
6fc675f43ea490852e171cb978a9b9442c5f565d | Oscar883/AprendiendoPython | /Concatenacion.py | 443 | 4.1875 | 4 | #Se declaran dos variables con input para ingresar la informacion
#necesaria en este caso nombre y apellido
nombre=input("Nombre:")
apellidos=input("Apellidos:")
#Se concatenan los valores str, junto con la literal " " (para tomar un espacio)
NombreCompleto=nombre+" "+apellidos
#Se asigna a la variable la represe... | false |
e294f151d8eaded0356ab30f0cc961a31aff3698 | vishnuvs369/python-tutorials | /inputs.py | 421 | 4.21875 | 4 | # inputs
name = input("Enter your name")
email = input("Enter your email")
print(name , email)
#-------------------------------------------------
num1 = input("Enter the first number") #The input number is in string we need to convert to integer
num2 = input("Enter the second number")
#num1 = int(input("Enter... | true |
0bddc508ce2a5079507fdd0dbe4f55a0c09a2ef7 | Joezeo/codes-repo | /python-pro/io_prac.py | 508 | 4.15625 | 4 | forbideen = ('!', ',', '.', ';', '/', '?', ' ')
def remove_forbideen(text):
text = text.lower()
for ch in text:
if ch in forbideen:
text = text.replace(ch, '')
return text
def reverse(text):
return text[::-1]# 反转字符串
def is_palindrome(text):
return text == reverse(text)
in... | true |
6e83d95f12ae67d956867620574d63000b4ed848 | famosofk/PythonTricks | /ex/dataStructures.py | 800 | 4.40625 | 4 | #tuples
x = ('string', 3, 7, 'bh', 89)
print(type(x))
#tuples are imatuble. This is a list of different types object. We create tuples using (). In python this would be listof
y = ["fabin", 3, "diretoria", 8, 73]
y.append("banana")
print(type(y))
#lists are mutable tuples. We create lists using []
#both of them are ... | true |
03dae7a8d59866b3c788c42fbc5c43a09d4e89ef | famosofk/PythonTricks | /2-DataStructures/week3/files.py | 739 | 4.3125 | 4 | # to read a file we need to use open(). this returns a variable called file handler, used to perform operations on file.
#handle = open(filename, mode) #Mode is opcional. If you plan to read, use 'r', and use 'w' if you want to write
#each line in file is treated as a sequence of strings, so if you want to print
name ... | true |
8a781a70cc04d0d89c28c3db8da5d5ee0e9b49da | AhmadAli137/Base-e-Calculator | /BorderHacks2020.py | 1,521 | 4.34375 | 4 | import math #library for math operation such as factorials
print("==============================================")
print("Welcome to the Exponent-Base-e Calculator:")
print("----------------------------------------------")
print(" by Ahmad Ali ") #Prompts
print(" (BorderHacks 2020... | true |
ee5ff425f61a596cc7edddb5bc3b11211cdc2e56 | urandu/Random-problems | /devc_challenges/interest_challenge.py | 938 | 4.21875 | 4 |
def question_generator(questions):
for question in questions:
yield question.get("short") + input(question.get("q"))
def answer_questions(questions):
output = "|"
for answer in question_generator(questions):
output = output + answer + " | "
return output
questions = [
{
... | true |
96a39f4843822454b01e4ab1506825bd053518ca | Linkin-1995/test_code1 | /day05/homework/exercise06(弹球高度while).py | 808 | 4.40625 | 4 | """
6. 一个小球从100m高度落下,每次弹回原高度一半.
计算:
-- 总共弹起多少次?(最小弹起高度0.01m) 13 次
-- 全过程总共移动多少米?
"""
height = 100
count = 0
distance = height # 开始落下 -- 计算初始高度
# 判断弹之前的高度height
# 判断弹之后的高度height / 2
# 0.01 弹起来的最小高度
while height / 2 > 0.01:
# 弹起来
height /= 2
count += 1
distance += height * 2 # 弹起过程 -- 累加起落距... | false |
83ac9d92121137cce3d7c1bc53e375432a10cae8 | Linkin-1995/test_code1 | /day07/demo05(两层for).py | 597 | 4.28125 | 4 | """
for for
练习:exercise04
"""
"""
print("#", end=" ")
print("#", end=" ")
print("#", end=" ")
print("#", end=" ")
print("#", end=" ")
print() # 换行
print("#", end=" ")
print("#", end=" ")
print("#", end=" ")
print("#", end=" ")
print("#", end=" ")
print() # 换行
print("#", end=" ")
print("#", end=" ")
print("#... | false |
0133e987d946fc4e4d9672eca7afc40c69809fb9 | Linkin-1995/test_code1 | /day09/homework/exercise03(输数字查课程名:简化版).py | 811 | 4.21875 | 4 | """
练习:参照day03/exercise05案例,
定义函数,根据课程编号计算课程名称。
if course == "1":
print("Python语言核心编程")
elif course == "2":
print("Python高级软件技术")
elif course == "3":
print("Web 全栈")
elif course == "4":
print("网络爬虫")
elif course == "5":
print("数据分析、人工智能")
"""
def g... | false |
ed9548882b35f9957bf9a9008cfeaea36ef4a508 | Linkin-1995/test_code1 | /day13/demo01(复合运算符重载).py | 758 | 4.25 | 4 | class Vector2:
"""
二维向量
"""
def __init__(self, x, y):
self.x = x
self.y = y
# + :创建新数据
def __add__(self, other):
return Vector2(self.x + other.x, self.y + other.y)
# +=:尽量在原有基础上改变(不可变对象只能创建新,可变对象不创建新)
def __iadd__(self, other):
self.x += other.x
... | false |
da69bc85053c2d6ca956cae41f7c9d7f87d774d2 | Linkin-1995/test_code1 | /day06/demo03(浅拷贝内存图).py | 303 | 4.28125 | 4 | """
列表内存图
列表嵌套
浅拷贝
"""
list01 = [
"a",
["b", "c"]
]
# 浅拷贝,只备份一层数据(两份)
# 第二层数据只有一份
list02 = list01[:]
list01[0] = "A" # 修改第一层
list01[1][0] = "B" # 修改第二层
print(list02) # ['a', ['B', 'c']]
| false |
06f2ebe240539323ed232937bd118ce44ed6f9cf | Linkin-1995/test_code1 | /day04/demo03.py | 401 | 4.28125 | 4 | """
while 循环 - 循环计数
语法:
count = 0 # 循环前 -- 开始值
while count < 5: # 循环条件 -- 结束值
循环体
count += 1 # 循环体 -- 间隔
作用:
固定次数的重复
练习:exercise02~04
"""
# 执行5次
count = 0
while count < 5:
# print("跑圈")
print(count)
count += 1 # 0 1 2 3 4
| false |
71bd0c8d1b96b291eff6f280315e1b4f85b349fb | Linkin-1995/test_code1 | /day09/exercise04(星号args).py | 262 | 4.15625 | 4 | # 练习:定义数值累乘的函数
# 1,2,3,4
# 4,54,5,56,67,78,89
def multiplicative(*args):
result = 1
for number in args:
result *= number
return result
print(multiplicative(1, 2, 3, 4))
print(multiplicative(4, 54, 5, 56, 67, 78, 89))
| false |
26cffb891edbf40f373f56458f44427cf2c03d92 | Isaac-Yuri/menu-de-opcoes-matematicas | /principal.py | 1,798 | 4.34375 | 4 | from funcoes import menu, linha, continuar
from math import sqrt
while True:
print('===> SUAS OPÇOES <===')
menu()
linha(23)
opcao = int(input('Digite sua opção: '))
if opcao == 1:
while True:
num = int(input('Digite um número para checar se é par ou ìmpar: '))
linh... | false |
c44ca53b2a11e083c23a725efcb3ac17df10d8ee | bowersj00/CSP4th | /Bowers_MyCipher.py | 1,146 | 4.28125 | 4 | alphabet=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
def shifter(start_string, shift):
new_string=""
for character in start_string:
if character.isalpha():
new_string=new_string+(alphabet[(alphabet.index(character)+shift)%26])
... | true |
e486049e3ee77222325cf474606cb0886ac13e35 | Ryoichi-Ueno/Self_Taught | /challenge13_1.py | 1,409 | 4.125 | 4 | class Shape:
def __init__(self):
self.my_name = 'I am shape!'
def what_am_i(self):
print(self.my_name)
class Rectangle(Shape):
def __init__(self, base, height):
super().__init__()
self.base = base
self.height = height
def calculate_perimeter(self):
... | false |
d86b80e7d3283ff2ee1b062e14539dbb87e34206 | anillava1999/Innomatics-Intership-Task | /Task 2/Task3.py | 1,778 | 4.40625 | 4 | '''
Given the names and grades for each student in a class of students, store them in a nested list and print the name(s) of any student(s) having the second lowest grade.
Note: If there are multiple students with the second lowest grade, order their names alphabetically and print each name on a new line.
Example
... | true |
3664b39e29387cb4c7beb0413249014d34b132bc | Arsalan-Habib/computer-graphics-assignments | /mercedez-logo/main.py | 1,719 | 4.21875 | 4 | import turtle
# initializing the screen window.
canvas = turtle.Screen()
canvas.bgcolor('light grey')
canvas.title('Mercedez logo')
# initializing the Turtle object
drawer = turtle.Turtle()
drawer.shape('turtle')
drawer.speed(3)
# Calculating the radius of the circumscribing circle of the triangle.
# The formula is:... | true |
49fb9f94501503eedfd7f5913efb3c8ffe656e68 | Saij84/AutomatetheBoringStuff_Course | /src/scripts/12_guessNumber.py | 968 | 4.3125 | 4 | import random
#toDo
'''
-ask players name
-player need to guess a random number between 1 - 20
-player only have 6 guesses
-player need to be able to input a number
-check need to be performed to ensure number us between 1 - 20
-check that player is imputing int
-after input give player hint
-"Your guess i... | true |
d28b91aa36ee49eb6666a655e1ef9fb6239b1413 | geisonfgf/code-challenges | /challenges/find_odd_ocurrence.py | 701 | 4.28125 | 4 | """
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.
Input = [1, 2, 3, 2, 3, 1, 3]
Expected result = 3
"""
def find_odd_ocurrence(arr):
result = 0
for i in xrange(len(arr)):
... | true |
7eb356997cc0862b77e09a80699b1681f0b51952 | geisonfgf/code-challenges | /challenges/evaluate_reverse_polish_notation.py | 560 | 4.21875 | 4 | """
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
"""
def evaluate(expression):
stack = []
while expression:
val = expression.pop(0)
if (str(val) == "+" or str(val) == "*" or
str(val) == "-" or str(val) == "/"):
x, ... | false |
1758af802adc1bf5dbf6b10bf4c04fd19d48e975 | mk9300241/HDA | /even.py | 209 | 4.34375 | 4 | #Write a Python program to find whether a given number (accept from the user) is even or odd
num = int(input("Enter a number:"))
if (num%2==0):
print(num," is even");
else:
print(num," is odd");
| true |
8712ae37e691e8e0c135a5d10601beac865591c3 | tussharbhatt/all_projects | /PycharmProjects/MyOwnStuff/data_Structure_progs/remove_common.py | 293 | 4.125 | 4 |
def main():
items=[]
for i in range(5):
items.append(input("enter values "))
dict={}
for item in items:
#print(item)
if item not in dict:
dict['key']=item
#for keys in dict.items():
print(dict['key'])
main() | false |
9979472aca0ae85cffffb3ddbee68ecb7a3d4b01 | tussharbhatt/all_projects | /PycharmProjects/pyStart/syntax_test.py | 405 | 4.21875 | 4 |
import datetime
#date1=datetime.datetime.now()
#print(now)
#print(now._day)
#date=datetime.datetime(date1._year,date1._month,date1._day)
'''def print_date(now1):
date1=now1
date2=datetime.date(,now1.month,now1.day)
print(date2)
'''
now=datetime.date.today()
#print_date(now)
year=int(input(... | false |
8bd4e4cdb8f32f99c9c0683aa454a4719f0ece73 | quinn3111993/nguyenphuongquynh-lab-c4e21 | /lab3/calc.py | 610 | 4.25 | 4 | # x = int(input("x = "))
# op = input("Operation(+, -, *, /): ")
# y = int(input("y = "))
# if op == '+':
# z = x + y
# print(x, '+', y, '=', z)
# elif op == '-':
# z = x - y
# print(x, '-', y, '=', z)
# elif op == '*':
# z = x * y
# print(x, '*', y, '=', z)
# elif op == '/':
# z = x / y
# ... | false |
3c16a7d51658806c1233e14640f6ce6d3cabda12 | voksmart/python | /QuickBytes/StringOperations.py | 1,601 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Sep 11 13:35:40 2019
@author: Mohit
"""
# String Assignment
str1 = "Hello"
str2 = "John"
# Checking String Length
print("Length of String is :",len(str1))
# String Concatenation (join)
print(str1 + " "+str2)
# String Formatting
# inserting name of guest a... | true |
c5e7b72cabf084c40320d31eb089b93451d7072d | ErosMLima/python-server-connection | /average.py | 217 | 4.375 | 4 | num = int(input("how many numbers ?"))
total_sum = 0
for n in range (num):
numbers = float(input("Enter any number"))
total_sum += numbers
avg = total_sum / num
print('The Average number is?'. avg) | true |
3a926ac51f31f52184607c8e4b27c99b4cbb9fb8 | AnujPatel21/DataStructure | /Merge_Sort.py | 863 | 4.25 | 4 | def merge_sort(unsorted_list):
if len(unsorted_list) <= 1:
return unsorted_list
middle = len(unsorted_list) // 2
left_half = unsorted_list[:middle]
right_half = unsorted_list[middle:]
left_half = merge_sort(left_half)
right_half = merge_sort(right_half)
return list(merge(left_half,... | true |
9fe71cad659e416a3c9349114ceebacae3895b15 | 12agnes/Exercism | /pangram/pangram.py | 317 | 4.125 | 4 | def is_pangram(sentence):
small = set()
# iterate over characters inside sentence
for character in sentence:
# if character found inside the set
try:
if character.isalpha():
small.add(character.lower())
except:
raise Exception("the sentence is not qualified to be pangram")
return len(small) == 26 | true |
c5a777c88c3e6352b2890e7cc21d5df29976e7e7 | edwardcodes/Udemy-100DaysOfPython | /Self Mini Projects/turtle-throw/who_throw_better.py | 1,371 | 4.3125 | 4 | # import the necessary libraries
from turtle import Turtle, Screen
import random
# Create custom screen
screen = Screen()
screen.setup(width=600, height=500)
guess = screen.textinput(title="Who will throw better",
prompt="Guess which turtle will throw longer distance?")
colors = ["red", "orang... | true |
8680ed0c79f30dead7add45ccba90fa253374d76 | Nam1130Tx/Python | /Python Assignments/abstraction.py | 597 | 4.28125 | 4 | #Python: 3.9.0
#Author: Nicholas Mireles
#Assignment: Abstraction Assignment
from abc import ABC, abstractmethod
class Shapes(ABC):
def sides(self):
print('How many sides does a ')
@abstractmethod
def num(self):
pass
class Triangle(Shapes):
def num(self):
... | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.