blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
62bbb74e43256f78b67050821d847af478d4669c | netor27/codefights-solutions | /arcade/python/arcade-intro/12_Land of Logic/052_longestWord.py | 637 | 4.21875 | 4 | def longestWord(text):
'''
Define a word as a sequence of consecutive English letters. Find the longest word from the given string.
'''
maxLen, maxStart, currStart, currLen = 0, 0, 0, 0
for i in range(len(text)):
if text[i].isalpha():
if currLen == 0:
currSta... | true |
6cc342813a5cf0ab9e54f0ebb7bf05911b66e9b0 | netor27/codefights-solutions | /arcade/python/arcade-theCore/05_ListForestEdge/040_IsSmooth.py | 996 | 4.125 | 4 | def isSmooth(arr):
'''
We define the middle of the array arr as follows:
if arr contains an odd number of elements, its middle is the element whose index number
is the same when counting from the beginning of the array and from its end;
if arr contains an even number of elements, its midd... | true |
df112813c067411853941f8455d31fed51a2c1fa | netor27/codefights-solutions | /arcade/python/arcade-theCore/01_IntroGates/005_MaxMultiple.py | 349 | 4.21875 | 4 | def maxMultiple(divisor, bound):
'''
Given a divisor and a bound, find the largest integer N such that:
N is divisible by divisor.
N is less than or equal to bound.
N is greater than 0.
It is guaranteed that such a number exists.
'''
num = bound - (bound % divisor)
return max(0, nu... | true |
4360bfb5399e8fc6a7d7453b8582063d04704139 | netor27/codefights-solutions | /arcade/python/arcade-intro/02_Edge of the Ocean/008_matrixElementsSum.py | 1,100 | 4.1875 | 4 | def matrixElementsSum(matrix):
'''
After they became famous, the CodeBots all decided to move to a new building
and live together. The building is represented by a rectangular matrix of rooms.
Each cell in the matrix contains an integer that represents the price of the room.
Some rooms are free (... | true |
9ab6e5d04bdd7d278e9f6c1188160ff8ae892e14 | netor27/codefights-solutions | /arcade/python/arcade-theCore/04_LoopTunnel/029_AdditionWithoutCarrying.py | 763 | 4.375 | 4 | def additionWithoutCarrying(param1, param2):
'''
A little boy is studying arithmetics.
He has just learned how to add two integers, written one below another, column by column.
But he always forgets about the important part - carrying.
Given two integers, find the result which the little boy ... | true |
cb03a35c7e74fc7ca73545dadc59c16bce5c6f7a | netor27/codefights-solutions | /arcade/python/arcade-theCore/08_MirrorLake/059_StringsConstruction.py | 634 | 4.1875 | 4 | def stringsConstruction(a, b):
'''
How many strings equal to a can be constructed using letters from the string b? Each letter can be used only once and in one string only.
Example
For a = "abc" and b = "abccba", the output should be
stringsConstruction(a, b) = 2.
We can construct 2 strings a with letters fr... | true |
5cf96612d1c9bdb7f2fd851e8a00b424c2da2b6f | mixelpixel/CS1-Code-Challenges | /cc69strings/strings.py | 2,486 | 4.28125 | 4 | # cc69 strings
# https://repl.it/student/submissions/1855286
# https://developers.google.com/edu/python/
# http://pythoncentral.io/cutting-and-slicing-strings-in-python/
'''
For this challenge, you'll be writing some basic string functions.
Simply follow along with each exercise's prompt.
You may find the following a... | true |
c2bad1043e0499dfcd0fed9d617d9200ebede882 | lijerryjr/MONIAC | /textFunctions.py | 1,637 | 4.21875 | 4 | ###################
# rightJustifyText
# This contains the text justifier code from HW3
###################
import string
def replaceWhiteSpace(text):
#replace white space in text with normal spaces
#inspired by recitation 3 video
inWhiteSpace=False
result=''
for c in text:
if not inWhiteSp... | true |
4c92c735e5966ba9de1cd9c0538c82040271139a | cloudsecuritylabs/pythonProject_1 | /ch_01/19.comparisonoperators..py | 812 | 4.125 | 4 | '''
Let's learn about comparison operators
'''
age = 0
if age <= 100:
print("You are too young")
elif age >100:
print("You are a strong kid")
else:
print("We need to talk")
if True:
print("hey there")
# this does not print anything
if False:
print("Oh No!")
string = "he he"
if string:
prin... | true |
da2004b72fdf6dc722bd025c1c6580a9e9aaed8e | ahmad-atmeh/my_project | /CA10/3.py | 592 | 4.34375 | 4 |
# 3.You are given a list of words. Write a function called find_frequencies(words) which returns a dictionary of the words along with their frequency.
# Input: find_frequencies(['cat', 'bat', 'cat'])
# Return: {'cat': 2, 'bat': 1}
# Creating an empty dictionary
def find_frequencies(word):
freq ={}
fo... | true |
36cda705b3d2e83c671be0582bbaf1cb45b7484d | ahmad-atmeh/my_project | /CA10/4.py | 384 | 4.125 | 4 |
#4. You are given a list of integers. Write a function cumulative_sum(numbers) which calculates the cumulative sum of the list. The cumulative sum of a list numbers = [a, b, c, ...] can be defined as [a, a+b, a+b+c, ...].
# Input: numbers = [1, 2, 3, 4]
# Return: cumulative_sum_list = [1, 3, 6, 10]
lis = [1, 2, 3, 4]... | true |
2e2eccaa840f0fbf6bde633cf87834b7b4b62173 | ahmad-atmeh/my_project | /CA07/Problem 3/circle.py | 2,002 | 4.46875 | 4 | # Class Circle
import math
class Circle:
# TODO: Define an instance attribute for PI
def __init__(self, radius=1.0):
# TODO: Define an instance attribute for the radius
self.PI=3.14
self.radius=radius
# TODO: Define the string represent... | true |
eb954e96ab4f8a34e70891920d417a2d93822b44 | Dipin-Adhikari/Python-From-Scratch | /Dictionary/dictionary.py | 1,398 | 4.125 | 4 | """Dictionaries is collection of keyvalue pairs.it is ordered and changeable but it doesnot allow duplicates values.."""
dictionary = {
"python": "Python is an interpreted high-level general-purpose programming language.",
"django": "Django is a Python-based free and open-source web framework that follows the ... | true |
b578a4a9a57922b7b6a13472a074c1ad883b0421 | Aadit017/code_sharing | /month to days.py | 756 | 4.1875 | 4 | while True:
name=input("Enter name of month: ")
name=name.lower()
if(name=="january"):
print("days=31")
elif(name=="february"):
print("days=28")
elif(name=="march"):
print("days=31")
elif(name=="april"):
print("days=30")
elif(name=="may"):
... | true |
a6759a0d5fb17142435d89d87ccbd4ce64629a39 | Abhilash11Addanki/cspp1-assignments | /Module 22 Week Exam/Check Sudoku/check_sudoku.py | 1,741 | 4.28125 | 4 | '''
Sudoku is a logic-based, combinatorial number-placement puzzle.
The objective is to fill a 9×9 grid with digits so that
each column, each row, and each of the nine 3×3 subgrids that compose the grid
contains all of the digits from 1 to 9.
Complete the check_sudoku function to check if the given... | true |
174ca0fb814021e716969bcd6b681fca98d5fbb9 | Abhilash11Addanki/cspp1-assignments | /Practice Problems/Code Camp matrix/matrix_operations.py | 2,042 | 4.125 | 4 | '''Matrix operations.'''
def mult_matrix(m_1, m_2):
'''
check if the matrix1 columns = matrix2 rows
mult the matrices and return the result matrix
print an error message if the matrix shapes are not valid for mult
and return None
error message should be "Error: Matrix shapes ... | true |
6485a65aaf4ecbcdbf3e86c954a792aeaa5c8948 | BabaYaga007/Second-1 | /stone_paper_scissor.py | 1,198 | 4.1875 | 4 | from random import randint
def print_menu():
print('1 for Stone')
print('2 for Paper')
print('3 for Scissor')
print('Enter your choice')
def print_score(a,b):
print('---Score---')
print('Player =',a)
print('Computer =',b)
choice = ['stone','paper','scissor']
a=0
b=0
while(... | true |
238f30f035a54ede9b8a3cae148c074bbd806ec3 | ralsouza/python_data_structures | /section7_arrays/searching_an_element.py | 440 | 4.1875 | 4 | from array import *
arr1 = array("i", [1,2,3,4,5,6])
def search_array(array, value):
for i in array: # --------------------------------------> O(n)
if i == value:# ------------------------------------> O(1)
return array.index(value) # --------------------> O(1)
return "The element does no... | true |
3f9c04833a87be9b112078e462c08aa7369dc9bc | ralsouza/python_data_structures | /section8_lists/chal6_pairs.py | 550 | 4.21875 | 4 | # Pairs
# Write a function to find all pairs of an integer array whose sum is equal to a given number.
# Example: pair_sum([2,4,3,5,6,-2,4,7,8,9], 7)
# Output: ['2+5', '4+3', '3+4', '-2+9']
my_list = [2,4,3,5,6,-2,4,7,8,9]
def pair_sum(list, num_sum):
output = []
for i in range(len(list)):
for j in r... | true |
49ab45268ba1099af5637316d5584e075a601dab | ralsouza/python_data_structures | /section28_sorting_algorithms/293_bubbles_sort.py | 490 | 4.25 | 4 | # Bubble Sort
# - Bubble sort is also referred as Sinking sort
# - We repeatedly compare each pair of adjacent items and swap them if
# they are in the wrong order
def bubble_sort(custom_list):
for i in range(len(custom_list)-1):
for j in range(len(custom_list)-i-1):
if custom_list[j] > custo... | true |
6adcebfeff79bf2c97bf0587a49e658e71b7b503 | ralsouza/python_data_structures | /section8_lists/proj3_finding_numer_in_array.py | 399 | 4.15625 | 4 | # Project 3 - Finding a number in a array
# Question 3 - How to check if an array contains a number in Python
import numpy as np
my_list = list(range(1,21))
my_array = np.array(my_list)
def find_number(array, number):
for i in range(len(array)):
if array[i] == number:
print(f"The number {numb... | true |
c22fbab5afe23a79783eeaa86b6d0041c5c01b7d | viratalbu1/Python- | /AccesingInstanceVariable.py | 513 | 4.25 | 4 | #This Example is used for understanding what is instance variable
class test:
def __init__(self,name,rollno):
self.name=name
self.rollno=rollno
def info(self):
print(self.name)
print(self.rollno)
#In Above Example state creation of constructor and object method
# For Accessing it just create Obje... | true |
78e9924735898785f3963c59531b866f1f44138b | viratalbu1/Python- | /IteratorAndGeneratorExample.py | 695 | 4.875 | 5 | # Iterator is used for creating object for iteratable object such as string, list , tuple
itr_list=iter([1,2,3,4])
itr_tuple=iter((1,2,3,4))
itr_string=iter('String')
print('--------List ------')
for val in itr_list:
print(val)
print('-----Tuple----------')
for val in itr_tuple:
print(val)
print('--... | true |
ad96b449267f2c830b6ebc0f6f0d8f13a1300f0a | bongjour/effective_python | /part1/zip.py | 672 | 4.15625 | 4 | from itertools import zip_longest
names = ['dante', 'beerang', 'sonic']
letters = [len(each) for each in names]
longest_name = None
max_letter = 0
# for i, name in enumerate(names):
# count = letters[i]
#
# if count > max_letter:
# longest_name = name
# max_letter = count
for name, count i... | true |
4f1ee7021d8707fcf351345b18d164ecc0ccd3db | aFuzzyBear/Python | /python/mystuff/ex24.py | 1,953 | 4.28125 | 4 | # Ex24- More Python Practicing
#Here we are using the escape \\ commands int eh print statement.
print "Let's practice everything."
print "You\'d need to know \'bout dealing with \\escape statements\\ that do \n newlines and \t tabs"
#Here we have made the poem a multilined print statement
poem = """
\tThe lovely wor... | true |
09f90dc3135c90b4e3a62d3ef3553f160c621f4a | aFuzzyBear/Python | /python/mystuff/ex33.py | 1,228 | 4.375 | 4 | #While Loops
"""A While loop will keep executing code if the boolean expression is True. It is a simple If-Statement but instead of running a block of code once if True, it would keep running through the block untill it reaches the first False expression.
The issue with while-loops is that they sometimes dont stop. Th... | true |
1766f40560f8a404a0c964a89198d185304c20c7 | aFuzzyBear/Python | /python/mystuff/ex20.py | 606 | 4.15625 | 4 | #Functions and Files
from sys import argv
scrit, input_file = argv
def print_all(f):
print f.read()
def rewind (f):
f.seek(0)
def print_a_line(line_count, f):
print line_count, f.readline()
current_file = open(input_file)
print "First let's print the whole file: \n"
print_all(current_file)
print "Now let's ... | true |
d37e27a702a74af02dce7b41c3a6a368f714ba2e | szhongren/leetcode | /129/main.py | 1,697 | 4.15625 | 4 | """
Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.
An example is the root-to-leaf path 1->2->3 which represents the number 123.
Find the total sum of all root-to-leaf numbers.
For example,
1
/ \
2 3
The root-to-leaf path 1->2 represents t... | true |
1a1a9e775108be74c02d4e90c42bf1928f94ca4f | szhongren/leetcode | /337/main.py | 2,378 | 4.15625 | 4 | """
The thief has found himself a new place for his thievery again. There is only one entrance to this area, called the "root." Besides the root, each house has one and only one parent house. After a tour, the smart thief realized that "all houses in this place forms a binary tree". It will automatically contact the p... | true |
522b1b01a64b08202f162b7fae780dbf2219066e | szhongren/leetcode | /473/main.py | 1,692 | 4.3125 | 4 | """
Remember the story of Little Match Girl? By now, you know exactly what matchsticks the little match girl has, please find out a way you can make one square by using up all those matchsticks. You should not break any stick, but you can link them up, and each matchstick must be used exactly one time.
Your input w... | true |
4671c9f8d366e45e97a92920d6190e1d7c65d894 | tdongsi/effective_python | /ep/item13b.py | 1,973 | 4.15625 | 4 |
NUMBERS = [8, 3, 1, 2, 5, 4, 7, 6]
GROUP = {2, 3, 5, 7}
def sort_priority(numbers, group):
""" Sort the input numbers but put those in "group" first.
:param numbers: list of input numbers.
:param group: set of numbers in priority group.
:return: True if any number in priority is found.
"""
f... | true |
6c73b0dade33e1a6dfbd3bfc1bb9e43ec21dabbf | tdongsi/effective_python | /ep/item13.py | 924 | 4.46875 | 4 |
meep = 23
def enclosing():
""" Variable reference in different scopes.
When referring to a variable not existing in the inner scope,
Python will try to look up in the outer scope.
"""
foo = 15
def my_func():
bar = 10
print(bar) # local scope
print(foo) # e... | true |
3d8fa1d96a89e06299f099b1f4ccc88cf33b5d97 | oigwe/learning_data_analyzing | /python/Step 1/2.Python Data Analysis Basics: Takeaways.py | 1,229 | 4.1875 | 4 | #Python Data Analysis Basics: Takeaways
#by Dataquest Labs, Inc. - All rights reserved © 2020
#Syntax
#STRING FORMATTING AND FORMAT SPECIFICATIONS
#Insert values into a string in order:
continents = "France is in {} and China is in {}".format("Europe", "Asia")
#Insert values into a string by position:
squares = "{0}... | true |
0a4042a5c22e529574bc1ccb8f1f6bbfad9c7894 | oigwe/learning_data_analyzing | /python/Step 1/Lists and For Loops: Takeaways.py | 1,567 | 4.375 | 4 | #Lists and For Loops: Takeaways
#by Dataquest Labs, Inc. - All rights reserved © 2020
#Syntax
#Creating a list of data points:
row_1 = ['Facebook', 0.0, 'USD', 2974676, 3.5]
row_2 = ['Instagram', 0.0, 'USD', 2161558, 4.5]
#Creating a list of lists:
data = [row_1, row_2]
#Retrieving an element of a list:
first_row ... | true |
28d231a0a4e9f1a42c968643e77bd1598e0da992 | jonag-code/python | /dictionary_list_tuples.py | 1,675 | 4.25 | 4 | List =[x**2 for x in range(5)]
Dictionary = {0:'zero', 1:'one', 2:'four', 3:'nine', 4:'sixteen'}
Tuple = tuple(List)
#The following doesn't work as with lists: Tuple2 =(x**2 for x in range(10)).
#Also the entries of tuples cannot be modified like in lists or dictionaries.
#This is useful when storing import... | true |
4e5a34a5a570d67a33a414124f62dd3b498e06a2 | Robin-Andrews/Serious-Fun-with-Python-Turtle-Graphics | /Chapter 8 - The Classic Snake Game with Python Turtle Graphics/2. basic_snake_movement.py | 1,362 | 4.25 | 4 | # Import the Turtle Graphics module
import turtle
# Define program constants
WIDTH = 500
HEIGHT = 500
DELAY = 400 # Milliseconds between screen updates
def move_snake():
stamper.clearstamps() # Remove existing stamps made by stamper.
# Next position for head of snake.
new_head = snake[-1].copy()
... | true |
501ca8c5a71b67cd7db14e7577be41fcd6646fd7 | shantanusharma95/LearningPython | /DataStructures/priority_queue.py | 2,988 | 4.25 | 4 | import sys
class node:
def __init__(self,data,priority):
self.data=data
self.priority=priority
self.next=None
class queue:
def __init__(self):
self.Head=self.Tail=None
self.queueSize=0
#adds a new value to queue, based on priority of data
#this will make enqueu... | true |
08951c8a90dc3bffde4ce992e89a15ff0ba31acf | adudjandaniel/Fractions | /lib/fraction/fraction.py | 2,313 | 4.1875 | 4 | class Fraction():
'''A basic fraction data type in python'''
def __init__(self, a=0, b=1):
self.a = a
self.b = b if b else 1
def __str__(self):
'''Converts the instance to a string'''
return "{}/{}".format(self.a, self.b)
def __repr__(self):
'''View of the inst... | true |
41f9eaee34956ebf3e6688ebca4d55b095552448 | yafiimo/python-practice | /lessons/11_ranges.py | 992 | 4.21875 | 4 | print('\nloops from n=0 to n=4, ie up to 5 non-inclusive of 5')
for n in range(5):
print(n)
print('\nloops from 1 to 6 non-inclusive of 6')
for n in range(1,6):
print(n)
print('\nloop from 0 to 20 in steps of 4')
for n in range(0, 21, 4):
print(n)
print('\nloop through list like a for loop')
food = ['cha... | true |
842079f591bef1485312dad98a8d44ad0cbace44 | yafiimo/python-practice | /lessons/27_writing_files.py | 941 | 4.125 | 4 | # must use 'w' as 2nd argument to write to a file, and file_name as first argument
with open('text_files/write_file.txt', 'w') as write_file:
text1 = 'Hello, I am writing my first line to a file using Python!'
print('Writing first line to file...')
write_file.write(text1)
# if you want to ammend a file, yo... | true |
a40506eaf66ec0af19289816a30e8ff2039e5868 | zerodayz/dailycoding | /Examples/Recursion.py | 350 | 4.1875 | 4 | def recursive(input):
print("recursive(%s)" %input)
if input <= 0:
print("returning 0 into output")
return input
else:
print("entering recursive(%s)" %( input -1 ))
output = recursive(input -1)
print("output = %s from recursive(%s)" %(output, input - 1))
retur... | true |
fd0494ab43d057e55d61d3a0b0c2797406da3e47 | arpitsingh17/DataStructures | /binarysearch.py | 697 | 4.125 | 4 | # Binary Search
# Input list must be sorted in this search method.
def bin(alist,item):
aalist = alist
midterm = alist[(len(alist)//2)]
found = False
while True:
try:
if item < midterm:
#print (alist[:((alist.index(midterm)))])
return(bin(alist[:((alist.index(midte... | true |
d5b0e6cae118c886d8ac206b3af3e16ca0b4edf5 | j-thepac/Python_snippets | /SmallHighPow/smallhighpow.py | 896 | 4.21875 | 4 | """
We have the number 12385. We want to know the value of the closest cube but higher than 12385. The answer will be 13824.
Now, another case. We have the number 1245678. We want to know the 5th power, closest and higher than that number. The value will be 1419857.
We need a function find_next_power ( findNextPower ... | true |
08f2d5e5f13dcb98a8e419568b391b56439ae6cf | j-thepac/Python_snippets | /IntSeq/python/intseq.py | 1,626 | 4.21875 | 4 | """
Description:
Complete function findSequences. It accepts a positive integer n. Your task is to find such integer sequences:
Continuous positive integer and their sum value equals to n
For example, n = 15
valid integer sequences:
[1,2,3,4,5] (1+2+3+4+5==15)
[4,5,6] (4+5+6==15)
[7,8] (7+8==1... | true |
c7dfc6b9bbf3f103a6c4a127119edc8f0e0df1bd | j-thepac/Python_snippets | /Brackets/brackets.py | 1,423 | 4.21875 | 4 | """
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Every close bracket has a corresponding open bracket ... | true |
ebf04b862009e61e6993d8216c0ffdb3db6cf5a2 | j-thepac/Python_snippets | /SameCase/samecase.py | 1,069 | 4.1875 | 4 | """
Write a function that will check if two given characters are the same case.
'a' and 'g' returns 1
'A' and 'C' returns 1
'b' and 'G' returns 0
'B' and 'g' returns 0
'0' and '?' returns -1
If any of characters is not a letter, return -1.
If both characters are the same case, return 1.
If both characters are l... | true |
14c7bf781e52c8f4eaa62b0d30dab3939d452180 | j-thepac/Python_snippets | /Phoneno/phoneno.py | 1,032 | 4.21875 | 4 | """
Write a function that accepts an array of 10 integers (between 0 and 9)== that returns a string of those numbers in the form of a phone number.
Example
create_phone_number([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]) # => returns "(123) 456-7890"
The returned format must be correct in order to complete this challenge.
Don't fo... | true |
e362ff3a5d949f03cceb6f8de2602b06d1d2cac4 | barthelemyleveque/Piscine_Python | /D00/ex06/recipe.py | 2,559 | 4.125 | 4 | import sys
import time
cookbook= {
'sandwich': {
'ingredients':['ham', 'bread', 'cheese', 'tomatoes'],
'meal':'lunch',
'prep_time':10,
},
'cake' : {
'ingredients':['flour', 'sugar', 'eggs'],
'meal':'dessert',
'prep_time':60
},
'salad':{
'ingre... | true |
ce499afe3bf4323bc35f81eda9cb02bbeb866f2b | anand13sethi/Data-Structures-with-Python | /Queue/QueueReverse.py | 963 | 4.15625 | 4 | # Reversing a Queue implemented using singly link list using stack.
from QueueUsingLinkList import Queue
class Stack:
def __init__(self):
self.stack = []
self.size = 0
def is_empty(self):
return self.size <= 0
def push(self, data):
self.stack.append(data)
self.s... | true |
1b6bc1d29ff40669e1d3f47d92f5675934c4c8c8 | joeybtfsplk/projecteuler | /10.py | 1,353 | 4.125 | 4 | #!/usr/bin/env python
"""
file: 10.py
date: Thu Jul 31 09:25:11 EDT 2014
from: Project Euler: http://projecteuler.net
auth: tls
purp: The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of
all the primes below two million.
Ans: 142913828922 on Fri Aug 1 22:34:07 EDT 2014
"""
def prime_list(... | true |
0cd3f80f80bed75176e9ca50eb0f928d73df4cc6 | zw-999/learngit | /study_script/find_the_largest.py | 481 | 4.21875 | 4 | #!/usr/bin/env python
# coding=utf-8
import sys
def find_largest(file):
fi = open(file,"r")
for line in fi:
line = line.split()
print line
#fi.close()
#line = fi.readline()
largest = -1
for value in line.split():
v = int(value[:-1])
if v > largest:
... | true |
87424e37b3e029ddd8fcc1ccd752b23fc5864b33 | Kavitajagtap/Python3 | /Day8.py | 1,852 | 4.59375 | 5 |
# 1.Write a program to create dictionary and access all elements with keys and values
dict = eval(input("Enter dictionary = "))
print("Accessing Elements from dictionary -->")
for key in dict:
print(key,dict[key])
'''
Output :
Enter dictionary = {'Apple':2017,'Microsoft':1985,'Facebook':2012,'Amazon':1997}
Acces... | true |
71432b142344cfa33686bf7bdcaeafb4f2d4b372 | Kavitajagtap/Python3 | /Day16.py | 1,528 | 4.3125 | 4 |
"""
1. Write program to sort Counter by value.
Sample data : {'Math':81, 'Physics':83, 'Chemistry':87}
Expected data: [('Chemistry', 87), ('Physics', 83), ('Math', 81)]
"""
dict = {}
n = int(input("Enter elements: "))
for i in range(n):
k = (input("key: "))
v = int(input("value: "))
dict[k] = v
print("di... | true |
b369a56787f0a1d15519d7e228ac7ef2ef6b849a | VolodymyrMeda/Twittmap | /json_navigator.py | 1,646 | 4.1875 | 4 | import json
def reading_json(file):
'''
str -> dict
Function reads json file
and returns dictionary
'''
with open(file, mode='r', encoding='utf-8') as rd:
json_read = json.load(rd)
return json_read
def json_navigation(json_read):
'''
Function navigates user in
json d... | true |
a75fa80c8412141fd7e8b28978b5a7f92643fbed | annmag/Student-manager | /generator_function.py | 985 | 4.21875 | 4 | # Generator function - a way of crating iterators (objects which you can iterate over)
# Creating generator - defining function with at least one yield statement (or more) instead of return statement
# Difference: return terminates a function entirely
# yield pauses the function saving all it's states and continues ... | true |
0bd27accb7021db31fbfd540a9318d768adb366c | gokullogu/pylearn | /tutorial/list/add.py | 550 | 4.25 | 4 | #to add the the value to end of list use append
cars=["audi","bens","rolls royce"]
cars.append("bmw")
print(cars)
#['audi', 'bens', 'rolls royce', 'bmw']
#to append the list to the list use extend
fruit=["apple","mango","banana"]
veg=["carrot","beetroot","brinjal"]
fruit.extend(veg)
print(fruit)
#['apple', 'mango', 'b... | true |
50e3a4dbe8af7537d416e830a6882fcacf7fce1e | gokullogu/pylearn | /tutorial/list/remove.py | 778 | 4.28125 | 4 | #remove() removes item sepecified
fruit=["mango","orange","papaya"]
fruit.remove("mango")
print(fruit)
#['orange', 'papaya']
#pop() removes the list item at specified index
this_list=["john","19","poland"]
this_list.pop(1)
print(this_list)
#['john', 'poland']
#pop() removes the last item if unspecified
this_list1 =... | true |
bff509e7057885d4a0c7e480c09a4605db36bcb8 | ChadevPython/WeeklyChallenge | /2017/02-06-2017/EthanWalker/main.py | 240 | 4.3125 | 4 | #!/usr/bin/env python3
from reverse_str import reverse_line
import sys
#open file and get lines
with open(sys.argv[1], 'r') as in_file:
file = in_file.readlines()
# print reversed lines
for line in file:
print(reverse_line(line)) | true |
9a63728319bc7a007e3edcc2acf916c0e32b988a | Arunken/PythonScripts | /2_Python Advanced/8_Pandas/10_Sorting.py | 1,643 | 4.46875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jun 21 14:30:07 2018
@author: SilverDoe
"""
'''
There are two kinds of sorting available in Pandas :
1. By Label
2. By Actual Value
'''
'''================== Sorting By Label ========================================'''
import pandas as pd
import numpy as n... | true |
991d140f7e4100ae35f740c3b97f1ed62de4e7f9 | Krishnaarunangsu/LoggingDemonstration | /python_slice_1.py | 1,427 | 4.5 | 4 | # The slice() constructor creates a slice object representing the set of indices specified by range(start, stop, step).
# The slice object is used to slice a given sequence (string, bytes, tuple, list or range) or any object which supports sequence protocol (implements __getitem__() and __len__() method).
# Slice obj... | true |
f718803b224aff52828ca1c194f63fdb8706e64f | yashshah4/python-2 | /ex6.py | 725 | 4.375 | 4 | #creating a string x with formatting method %d
x = "There are %d types of people." % 10
#creating further strings
binary = "binary"
do_not = "don't"
#creating a second string with string formatting method
y = "Those who know %s and those who %s" %(binary, do_not)
#printing the first two strings
print x
print ... | true |
07cf522b16d5d13d48a8a8422ea10b84a60c81b4 | Gladarfin/Practice-Python | /turtle-tasks-master/turtle_11.py | 319 | 4.1875 | 4 | import turtle
turtle.shape('turtle')
turtle.speed(100)
def draw_circle(direction, step):
angle=2*direction
for i in range(180):
turtle.forward(step)
turtle.left(angle)
step=2.0
turtle.left(90)
for i in range(0, 10, 1):
draw_circle(1, step)
draw_circle(-1, step)
step+=0.3
| true |
e0b4849d6bea59c51b50017d00ba93b5defb7963 | johnmarkdaniels/python_practice | /odd_even.py | 272 | 4.125 | 4 | num = int(input('Please input a number: '))
if num % 2 == 0:
print(f'Your number ({str(num)}) is an even number.')
if num % 4 == 0:
print('Incidentally, your number is evenly divisible by 4.')
else:
print(f'Your number ({str(num)}) is an odd number.')
| true |
508e4a3139bca354467178cbc2687416924599ea | Harpreetkaurpanesar25/python.py | /anagram.py | 267 | 4.1875 | 4 | #an anagram of a string is another string that contains same char, only the order of characters are different
def anagram(s1,s2):
if sorted(s1)==sorted(s2):
print("yes")
else:
print("no")
s1=str(input(""))
s2=str(input(""))
anagram(s1,s2)
| true |
56c6c4417ca6f8dd1bc1880957484ed343b2a81d | teayes/Python | /Experiments/Exp6.py | 731 | 4.15625 | 4 | class stringValidation:
def __init__(self):
self.open= ["[", "{", "("]
self.close= ["]", "}", ")"]
def validate(self,string):
stack = []
for char in string:
if char in self.open:
stack.append(char)
elif char in self.close:
p... | true |
77c6300b4d7a20a073b857c545c8d702eee86595 | AlexKasapis/Daily-Coding-Problems | /2019-02-23.py | 1,252 | 4.125 | 4 | # PROBLEM DESCRIPTION
# Given a sorted list of integers, square the elements and give the output in sorted order.
# For example, given [-9, -2, 0, 2, 3], return [0, 4, 4, 9, 81].
#
# SOLUTION
# Lets assume two pointers, pointing to the start and end of the list. The pointer which points to the number with the
# highest... | true |
527835943216d348696b0ad6ed7f8ba521e5a56d | afrahaamer/PPLab | /III Regular Expressions/1 RegEx Functions/findall/Metacharachters/ends with.py | 241 | 4.21875 | 4 | # $ - Pattern ends with
# ^ - Pattern starts with
import re
t = "Hello, How are you World"
# Checks if string ends with World?
x = re.findall("World$",t)
print(x)
# Checks if string starts with Hello
x = re.findall("^Hello",t)
print(x)
| true |
312c35e0ee73ce3aa7b0836cf8f594d030ac1054 | MostDeadDeveloper/Python_Tutorial_Exercises | /exercise3.py | 357 | 4.21875 | 4 | # Challenge - Functions Exercise
# Create a function named tripleprint that takes a string as a parameter
# and prints that string 3 times in a row.
# So if I passed in the string "hello",
# it would print "hellohellohello"
def tripleprint(val):
print(val*3)
return val*3
#tripleprint("hello")
# ^ - r... | true |
0340d501babc4af06989c1455a8026e0b76c7cc8 | bchhun/Codes-Kata | /prime_factors.py | 1,509 | 4.21875 | 4 | #coding: utf-8
"""
Compute the prime factors of a given natural number.
Bernard says: What is a prime factor ? http://en.wikipedia.org/wiki/Prime_factor
Test Cases ([...] denotes a list)
primes(1) -> []
primes(2) -> [2]
primes(3) -> [3]
primes(4) -> [2,2]
primes(5) -> [5]
primes(6) -> [2,3]
primes(7) -> [7]
primes(8... | true |
c3272a68e7f7705810f956609b24d6a6477d2faa | kimmvsrnglim/DigitalCrafts | /week2/print_triangle.py | 222 | 4.1875 | 4 | def triangle(height):
for x in range(0, height, 2):
space = " " * ((height - x)/2)
print space + "*" * (x + 1)
user_input = int(raw_input("What's the height of your triangle?"))
triangle (user_input)
| true |
ee0d216b772925a8a2713e8ed7be384cd2e4f5fd | xandhiller/learningPython | /stringTidbits.py | 454 | 4.40625 | 4 | print('Enter a string: ')
n = input()
print("\nLength of string is: " + str(len(n)))
print()
# Starting i at 1 because i determines the non-inclusive upper limit of string
# truncation.
for i in range(1, len(n)+1):
print("string[0:"+str(i)+"]: \t" + n[0:i])
print()
# Conclusions:
# The operator 'string[0:8]' ... | true |
b1c3fa918bcbc2fa1ac9f877291389d52eaf0278 | JuanDAC/holbertonschool-higher_level_programming | /0x06-python-classes/101-square.py | 1,910 | 4.5625 | 5 | #!/usr/bin/python3
"""File with class Square"""
class Square:
"""Class use to represent a Square"""
def __init__(self, size=0, position=(0, 0)):
"""__init__ constructor method"""
self.size = size
self.position = position
@property
def size(self):
return self.__size
... | true |
2aac08cdac3ed1a5dc6c875d5ebb9f91e900bb81 | daveshanahan/python_challenges | /database_admin_program.py | 1,848 | 4.15625 | 4 | log_on_info = {
"davids1":"MahonAbtr!n1",
"lydiam2":"Password1234",
"carlynnH":"scheduling54321",
"maryMcN":"Forecaster123",
"colinM":"paymentsG145",
"admin00":"administrator5",
}
print("Welcome to the database admin program")
username = input("\nPlease enter your username: ").strip... | true |
78fd793c2ca6e3021894ee562e7d7cc5ad32b990 | daveshanahan/python_challenges | /Quadratic_Equation_Solver_App.py | 1,261 | 4.375 | 4 | import cmath
# print introduction
print("Welcome to the Quadratic Equation Solver App")
print("\nA Quadratic equation is of the form ax^2 + bx + c = 0.")
print("Your solutions can be real or complex numbers.")
print("A complex number has two parts: a + bj")
print("Where a is the real portion and bj is the imag... | true |
c6ab0fa71832cc589f844da6120d509fedd04a15 | daveshanahan/python_challenges | /guess_my_number_game.py | 893 | 4.21875 | 4 | import random
print("Welcome to the Guess My Number App")
# gather user input
name = input("\nHello! What is your name: ").title().strip()
# generate random number
print("Well " + name + ", I am thinking of a number between 1 and 20.")
random_num = random.randint(1,20)
# initialise guess counter and get ... | true |
0deda362dc460620ab43364b17599182f1f12e87 | daveshanahan/python_challenges | /grade_point_average_calculator.py | 2,658 | 4.4375 | 4 | print("Welcome to the average calculator app")
# gather user input
name = input("\nWhat is your name? ").title().strip()
num_grades = int(input("How many grades would you like to enter? "))
print("\n")
# initialise list and append number of grades depending on user input
grades = []
for i in range(num_grades... | true |
a85f63d5cfc5b211612bb92d388bbfb9526de482 | davidac2007/python_tutorials | /numbers.py | 2,448 | 4.5 | 4 | # Python numbers
# There are three numeric types in Pythom:
# int
x = 1
# float
y =2.8
# complex
z = 1j
print(type(x))
print(type(y))
print(type(z))
# Int
# Int or integer, is a whole number, positive or negative, without decimals,
# of unlimited length.
x = 1
y = 366376429
z = -3255522
print(type(x))
print(t... | true |
9dda68c3e93388399b7d1026d82efa2d41ea26a5 | GuhanSGCIT/Trees-and-Graphs-problem | /The lost one.py | 2,750 | 4.375 | 4 | """
Shankar the Artist had two lists that were permutations of one another. He was very proud. Unfortunately, while transporting them
from one exhibition to another, some numbers were lost out of the first list. Can you find the missing numbers?
As an example, the array with some numbers missing, arr=[7,2,5,3,5,3]... | true |
60652845c16c2840261f73b47b9225abd39ca9b0 | GuhanSGCIT/Trees-and-Graphs-problem | /Spell Bob.py | 2,515 | 4.3125 | 4 | """
Varun likes to play with cards a lot. Today, he's playing a game with three cards. Each card has a letter written on the top face and
another (possibly identical) letter written on the bottom face. Varun can arbitrarily reorder the cards and/or flip any of the cards
in any way he wishes (in particular, he can le... | true |
4472990ca9ef518a8e02dfcd668a19b7fcefd1ab | GuhanSGCIT/Trees-and-Graphs-problem | /snake pattern.py | 1,244 | 4.28125 | 4 | """
Given an M x N matrix .In the given matrix, you have to print the elements of the matrix in the snake pattern.
i des
First line contains two space separated integers M,N,which denotes the dimensions of matrix.
Next for each M lines contains N space separated integers,denotes the values.
Odes
print the sn... | true |
6012371aef940cf255e34f4d6960533564924be4 | GuhanSGCIT/Trees-and-Graphs-problem | /Guna and grid.py | 1,212 | 4.125 | 4 | """
Recently, Guna got a grid with n rows and m columns. Rows are indexed from 1 to n and columns are indexed from 1 to m.
The cell (i,j) is the cell of intersection of row i and column j. Each cell has a number written on it. The number written
on cell (i,j) is equal to (i+j). Now, Guna wants to select some cells f... | true |
d0ae84a9f2cb762c24b70b92ea1cab0e3acbe92d | GuhanSGCIT/Trees-and-Graphs-problem | /Egg Dropping Puzzle-Samsung.py | 2,110 | 4.40625 | 4 | """
Suppose you have N eggs and you want to determine from which floor in a K-floor building you can drop an egg such that it doesn't break. You have to determine the minimum number of attempts you need in order find the critical floor in the worst case while using the best strategy.There are few rules given below.
... | true |
cbc7d523b97ec18e747d0955b769c475c6935aff | alfonso-torres/eng84_OOP_exercises | /Fizzbuzz.py | 1,403 | 4.4375 | 4 | # Exercise 1 - Fizzbuzz
# Write a program that outputs sequentially the integers from 1 to 100, but on some conditions prints a string instead:
# when the integer is a multiple of 3 print “Fizz” instead of the number,
# when it is a multiple of 5 print “Buzz” instead of the number,
# when it is a multiple of both 3 an... | true |
6ed4d522eed64bb845676e0b9bcbd24e21ffa1ff | taroserigano/coderbyte | /Arrays/Consecutive.py | 737 | 4.1875 | 4 | '''
Consecutive
Have the function Consecutive(arr) take the array of integers stored in arr and return the minimum number of integers needed to make the contents of arr consecutive from the lowest number to the highest number. For example: If arr contains [4, 8, 6] then the output should be 2 because two numbers ne... | true |
4d03565e948a1b5f093d0ff0cb589ead794f8d21 | taroserigano/coderbyte | /Trees & Graphs/SymmetricTree.py | 1,203 | 4.5 | 4 | '''
Symmetric Tree
HIDE QUESTION
Have the function SymmetricTree(strArr) take the array of strings stored in strArr, which will represent a binary tree, and determine if the tree is symmetric (a mirror image of itself). The array will be implemented similar to how a binary heap is implemented, except the tree ... | true |
75bb3cbcba0b24a5487276691650603e261e416d | mgomez9638/CIS-106-Mario-Gomez | /Assignment 8/Activity 1.py | 668 | 4.40625 | 4 | # Activity 1
# This program gives the user access to create a multiplication table.
# You simply begin with entering a value, entering a starting point, and the size of the table.
def getExpressions():
print("Enter the number of expressions")
expressions = int(input())
return expressions
def getValue... | true |
bf3a761daa923e3fc486c37ed4a522d4cbb57d45 | mgomez9638/CIS-106-Mario-Gomez | /Assignment 5/Activity 6.py | 2,061 | 4.34375 | 4 | # Activity 6
# This program is intended to determine how much paint is required to paint a room.
# It, also, expresses how much the gallons of paint cost.
def get_length():
length = float(input("Enter the length of the room(in feet): "))
return length
def get_width():
width = float(input("Enter the... | true |
3031e95c3286a9b596e179e6e08b8903b99625ba | mgomez9638/CIS-106-Mario-Gomez | /Assignment 4/Activity 3.py | 439 | 4.15625 | 4 | # Assignment Three
# This program gives the user access to calculate the distance in U.S. standard lengths.
# It converts miles into yards, feet, and inches.
print("Enter distance in miles: ")
miles = float(input())
yards = 1760 * miles
feet = 5280 * miles
inches = 63360 * miles
print("The distance in yards is " +... | true |
1c132cd8d307833a17f4860c3d0267c89e0f83c6 | Sridevi333/Python-Deep-Learning-Programming | /ICP2/wordsperline.py | 355 | 4.125 | 4 | fileName = input("Enter file name: ")
f = open(fileName, "r")
# Open file for input
lines=0
mostWordsInLine = 0
for lineOfText in f.readlines():
wordCount = 0
lines += 1
f1=lineOfText.split()
wordCount=wordCount+len(f1)
if len(f1) > mostWordsInLine:
mostWordsInLine = len(f1)
print ... | true |
1a0e41d3b08f4c98db46d0f7e01e7ae247b21298 | Chuukwudi/Think-python | /chapter8_exercise8_5.py | 2,544 | 4.28125 | 4 | '''
str.islower()
Return True if all cased characters in the string are lowercase and there is at least one cased character,
False otherwise.
'''
def any_lowercase1(s):
for c in s:
if c.islower():
return True
else:
return False
'''Here, the funtion takes th... | true |
a1af47bd51c847b5ec8815835a24f13e89aa3053 | ckaydevs/learning_python | /class/draw art/squre.py | 924 | 4.3125 | 4 | import turtle
def draw_square(some_turtle):
for i in range(1,5):
some_turtle.forward(100)
some_turtle.right(90)
def draw_art():
window=turtle.Screen()
window.bgcolor("red")
#Create the turtle brad- Draws a square
brad=turtle.Turtle()
brad.shape("turtle")
brad.color("yellow"... | true |
7a4f8c8d68bd58f1cd327f3e41bc09329a5c3e6a | joelgarzatx/portfolio | /python/Python3_Homework03/src/decoder.py | 752 | 4.125 | 4 | """
Decoder provided function alphabator(list) accepts an integer list,
which returns the list of integers, substituting letters of the alphabet
for integer values from 1 through 26
"""
def alphabator(object_list):
""" Accepts a list of objects and returns the objects from
the list, replacing inte... | true |
bb47cb2a447892832f217c28d2570902d1c9709e | AdamBorg/PracCP1404 | /Prac03/asciiTable.py | 774 | 4.21875 | 4 | def main():
lower = 33
upper = 127
num_entered = get_number(lower,upper)
print("{:>3} {:>6} \n".format(num_entered, chr(num_entered)))
print_ascii_table(lower, upper)
def get_number(lower,upper):
num_entered = 0
exit_character = 'e'
while num_entered < 33 or num_entered > 127 or exi... | true |
ae2357e9ae0dc6da9f2aef9c4bd6897259cf9018 | sstoudenmier/CSCI-280 | /Assignment5/PathNode.py | 1,798 | 4.15625 | 4 | '''
Class representing a map location being searched. A map location is defined by its (row,
column) coordinates and the previous PathNode.
'''
class PathNode:
def __init__(self, row=0, col=0, previous=None):
self.row = row
self.col = col
self.previous = previous
'''
Gets the row... | true |
3a41918c0f0137427561146e947191acd06963a5 | akash639743/Python_Assignment | /Dictionary.py | 912 | 4.5 | 4 | # Dictionary
#1. Create a Dictionary with at least 5 key value pairs of the Student
students={1:"akash",2:"rohit",3:"simran",4:"mohit",5:"sonam"}
print(students)
# 1.1. Adding the values in dictionary
students[6]="soni"
print(students)
# 1.2. Updating the values in dictionary
students.update({7: "mukesh"})
print(... | true |
b983ae86176ffd7877a2e0b6351249487a5215cd | akash639743/Python_Assignment | /Access_Modifiers.py | 2,223 | 4.125 | 4 | # Access Modeifiers
# 1. Create a class with PRIVATE fields
class Geek:
# private members
__name = None
__roll = None
__branch = None
# constructor
def __init__(self, name, roll, branch):
self.__name = name
self.__roll = roll
self.__branch = branch
# private member function
def __displayDetails(sel... | true |
eaf51afa470cdb8bb97633aa5d624075d47ba331 | dieg0varela/holbertonschool-higher_level_programming | /0x06-python-classes/5-square.py | 1,044 | 4.3125 | 4 | #!/usr/bin/python3
"""Define class Square"""
class Square:
"""Class Square"""
def __init__(self, new_size=0):
"""Init Method load size"""
if (isinstance(new_size, int) is False):
raise TypeError("size must be an integer")
if (new_size < 0):
raise ValueError("siz... | true |
3c8374bfdcac02646aa651cb2eca1f4b79f0dbb9 | thorenscientific/py | /TypeTrip/TypeTrip.py | 422 | 4.15625 | 4 | # A simple script demonstrating duck typing...
print "How trippy are Python Types??"
print "Let's start with x=1...."
x = 1
print "x's value:"
print x
print "x's type:"
print type(x)
print "Now do this: x = x * 1.01"
x = x * 1.01
print "x's value:"
print x
print "x's type:"
print type(x)
print "... | true |
c1ad2b3ac87e01b9a230b71b9aca5af6bb34d9ed | flora5/py_simple | /map_reduce_filter.py | 1,062 | 4.21875 | 4 | """
filter(function or None, sequence) -> list, tuple, or string
Return those items of sequence for which function(item) is true. If
function is None, return the items that are true. If sequence is a tuple
or string, return the same type, else return a list.
"""
str = ['a','b','c','d']
def func(s):
if ... | true |
f5df8af88f3449e2124e9cc0899300bc2eff9fb7 | mzanzilla/Python-For-Programmers | /Files/ex3.py | 1,239 | 4.5 | 4 | #Updating records in a text file
#We want to update the name for record number 300 - change name from White to Williams
#Updating textfiles can affect formattting because texts may have varrying length.
#To address this a temporary file will be created
import os
tempFile = open("tempFile.txt", "w")
accounts = open("acc... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.