blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
0ca94d662e3e9e12360d7281dc50ad1d385dad5e | nsimonova/GeekBrains | /Lesson_2/Task4.py | 543 | 4.15625 | 4 | # Пользователь вводит строку из нескольких слов, разделённых пробелами. Вывести каждое слово с новой строки.
# Строки необходимо пронумеровать. Если в слово длинное, выводить только первые 10 букв в слове.
new_string = input("Введите фразу ")
split_string = new_string.split()
for index, word in enumerate(split_string, ... | false |
fafb8be85bcf0e322db418832143041eef35f29a | rahulcs754/Python-script-example | /code/removing_Vowels.py | 237 | 4.375 | 4 | vowels = ("a","e","i","o","u")
message = input("Enter mesage: ")
new_message = ""
for letters in message:
if letters not in vowels:
new_message = new_message+letters
print("message without vowels: {}".format(new_message)) | false |
d40f3551ef866c7253c8432d86d95cfd06e094ef | sup3r-n0va/Python-3-Tutorial | /WhileLoops.py | 556 | 4.375 | 4 | #!/bin/python3
import os
import random
import sys
#This section is on while loops
#To initialise a random number generator
#This will generate a random number between 0 - 100
random_num = random.randrange(0, 100)
#this loop will loop through all the numbers until 42 is displayed
#while(random_num != 42) :
# print(... | true |
9ff96082847f94609d541f29483e9baaa113a6c5 | prusso/thebizbaz | /Python/simeonfranklin.com/class2.py | 450 | 4.25 | 4 | names = ['John', 'Luke', 'Paul', 'Mark', 'Richard', 'Christopher', 'Dan', 'Sam']
# Print all names in the list
for name in names:
print "Hello " + name
# Print last name
print "Hello " + names[-1]
# Print last two names
for name in names[6:]:
print "Hello " + name
# Print every other name
for name in names[::2]:
... | false |
2ddf142a4b01904609fe6814f6803b8a08e7a82e | Compro-Prasad/GLUG | /workshops/gettingComfortableWithPython/doc.py | 333 | 4.15625 | 4 | def add(*args):
"""Add all numbers provided as arguments. Example:
>>> add(1, 2, 3)
6
>>> add(*range(10))
45
>>> add(1, '2')
Traceback (most recent call last):
...
TypeError: unsupported operand type(s) for +=: 'int' and 'str'
"""
s = 0
for num in args:
s += num
... | true |
947db1d5d90878c51fc83d11d338aad870f1243d | devashish89/PluralsightPythonIntermediate | /ClosureEx1.py | 337 | 4.15625 | 4 | #Closure: is a inner function(local function) that remembers or have access to local variables when it was created even when outer function has finished
def outer(msg):
message = msg
def inner():
print(message)
return inner
f = outer("Hi")
print(f)
print(f.__name__) #inner()
f()
f()
f1 = outer("H... | true |
bf232d1dd9a62a42f633b8e9dd6b089da8dd0073 | araghava92/comp-805 | /labs/lab1.py | 1,134 | 4.25 | 4 | """
Jon Shallow
UNHM COMP705/805 Lab 1
An Introduction to Python
Jan 19, 2018
The purpose of this file is to learn BASIC python syntax and data structures.
There is an accompanying test file. Place both files in the same directory,
and then run:
$ python tests.py
You will see a print out of tests that are being run, ... | true |
c02f5beda0e255a9d7ff3a007923b808e7c8ccbb | lauirvin/algorithms-data-structures | /Week_3/Week3.py | 1,454 | 4.1875 | 4 | # 1. Write a program that reads n words from the standard input, separated by spaces and prints them mirrored (the mirroring function should be implemented recursively). What is the time complexity of the algorithm? Use the BigO notation to express it.
import unittest
import string
def reverseString(string):
if l... | true |
570085ceb4647d2701d89d54d5d579ea1b97b8f7 | kaustubhsingh/CodeSomething | /Algorithms/eulerian_tour.py | 696 | 4.21875 | 4 | # Find Eulerian Tour
#
# Write a function that takes in a graph
# represented as a list of tuples
# and return a list of nodes that
# you would follow on an Eulerian Tour
#
# For example, if the input graph was
# [(1, 2), (2, 3), (3, 1)]
# A possible Eulerian tour would be [1, 2, 3, 1]
graph = [(1, 2), (2, 3), (3, 1)]... | false |
f274b5e5e035d2a9f6adaf34a41b69b0211b3349 | luishmcmoreno/project-euler | /0019.py | 625 | 4.21875 | 4 | starting_day = 2
day = 1
month = 1
year = 1901
sundays = 0
while (year < 2001):
if (day == 1 and starting_day % 7 == 0):
sundays += 1
day += 1
starting_day += 1
if (month == 2):
if (year % 400 == 0 or (year % 4 == 0 and year % 100 != 0)):
if (day == 30):
day = 1
month = 3
else... | false |
d9837d605db1855343075007464824c9f33520cc | katyaryabova/HomeTask9 | /Task4.py | 358 | 4.1875 | 4 | month = int(input('Choose a month: '))
def seasons(a):
if a == 1 or a == 2 or a == 12:
print('Winter')
elif a == 3 or a == 4 or a == 5:
print('Sping')
elif a == 6 or a == 7 or a == 8:
print('Summer')
elif a == 9 or a == 10 or a == 11:
print('Autumn')
else:
p... | false |
915d9f255868e7c96b73e01111b900bf57a4d315 | gloria-aprilia/Exam-Purwadhika-JCDS10 | /Exam 1/TimeConverter.py | 1,037 | 4.125 | 4 | import math #add math library
def timeConverter(seconds): #define function
if type(seconds) == int and seconds >= 0 and seconds < 359999: #condition if the input is integer
hour = math.floor(seconds/3600) #calculate hour
hr_rem = seconds%3600 #see remaining second
minute = math.flo... | true |
001d520959faf86ef7fb9aa64e9010de1d1cea4f | denis19973/sorting_algorithms | /bubble.py | 1,680 | 4.375 | 4 | from copy import copy
def simple_bubble_sort(l: list):
"""
Max count of iterations for sorting all elements in list with n elements is n - 1.
for example: sorting [2, 1] needs 1 iteration; [3, 2, 1] needs 2 iterations
"""
iterations = 0
for _ in range(len(l) - 1):
for i in range(len(l) - 1):
iterations += ... | true |
4f485dbe3f2c7be3e008790b3e04eecac6de6a2b | hippietilley/COMP-1800 | /Scripts/(11-15) Building height calculator.py | 626 | 4.53125 | 5 | # This program computes the height of a building, given
# the angle measure to the top and the horizontal distance
# to the building's base.
import math
theta = float(input("Enter the angle measure to the top of the building (in degrees): "))
d = float(input("Enter the horizontal distance to the base of the ... | true |
5922a8428f5b23e51d864c91d3026f751f51e539 | hippietilley/COMP-1800 | /Scripts/Class examples/(9-29) Pizza ordering program.py | 705 | 4.25 | 4 | # This program computes the final price of a pizza order.
# Our store sells only three types of items:
# pizzas for $15 each
# side items for $7.50 each
# drinks for $4.99 each
# get user input
numPizzas = int(input("How many pizzas do you want? "))
numSides = int(input("How many sides do you want? "))
num... | true |
b0117f55d35964678d2575781acc0176cdd7cc23 | MoserMichael/pythoncourse | /09-functions.py | 1,662 | 4.53125 | 5 |
# Our programs were a sequence of sequence of statements, what would happen if we have two sequences of identical statements in the program that are used twice?
# Correct - we would have two copies of these sequences. This approach comes with its problems; if we find a bug in one instance,
# then we have to fix it ... | true |
c75e91bf9b13569d1941e88be09046252220f88d | Jimut123/code-backup | /python/coursera_python/FUND_OF_COMP_RICE/FUND_OF_COMPUTING_RICE2/week1/iter_lists.py | 985 | 4.21875 | 4 | def square_list1(numbers):
"""Returns a list of the squares of the numbers in the input."""
result = []
for n in numbers:
result.append(n ** 2)
return result
def square_list2(numbers):
"""Returns a list of the squares of the numbers in the input."""
return [n ** 2 for n in numbers]
pri... | true |
03dd82e95bb0909e7dd5c25783d017d052b2ee3d | Jimut123/code-backup | /python/coursera_python/RICE/PPE/date_m.py | 732 | 4.4375 | 4 | """
Demonstration of some of the features of the datetime module.
"""
import datetime
# Create some dates
print("Creating Dates")
print("==============")
date1 = datetime.date(1999, 12, 31)
date2 = datetime.date(2000, 1, 1)
date3 = datetime.date(2016, 4, 15)
# date4 = datetime.date(2012, 8, 32)
# Today's date
today... | true |
baa2722d280e1dae0866ccf297772f0cc81eb508 | Jimut123/code-backup | /python/coursera_python/FUND_OF_COMP_RICE/FUND_OF_COMPUTING_RICE2/week2/particle_random1.py | 1,426 | 4.125 | 4 | # Particle class example used to simulate diffusion of molecules
import simplegui
import random
# global constants
WIDTH = 600
HEIGHT = 400
PARTICLE_RADIUS = 5
COLOR_LIST = ["Red", "Green", "Blue", "White"]
DIRECTION_LIST = [[1,0], [0, 1], [-1, 0], [0, -1]]
# definition of Particle class
class Particle:
# ... | true |
cf3da63305700ddc1ae685d781c56fc97a35ed4f | Jimut123/code-backup | /python_gui_tkinter/Tkinter/TkinterCourse/33_sliders.py | 824 | 4.3125 | 4 | '''
A slider is a Tkinter object with which a user can set a value by moving an indicator. Sliders can be vertically or horizontally arranged. A slider is created with the Scale method().
Using the Scale widget creates a graphical object, which allows the user to select a numerical value by moving a knob along a scale... | true |
6e6bccda0b771bb7f3c16e14a937687b7ed0aeea | Jimut123/code-backup | /python/python_new/Python 3/elif.py | 213 | 4.40625 | 4 | #Program checks if the number is positive or negative# And displays an appropriate message
num=3.4
#num=0
#num=-4.5
if num>=0:
print("Positive number")
elif num==0:
print("Zero")
else:
print("Negative number")
| true |
2b73effba297e3453d24fccfe6423e4f3fc80c92 | Jimut123/code-backup | /python_gui_tkinter/Tkinter/TkinterCourse/34_sliders_1.py | 655 | 4.1875 | 4 | '''
We have demonstrated in the previous example how to create sliders. But it's not enough to have a slider, we also need a method to query it's value. We can accomplish this with the get method. We extend the previous example with a Button to view the values. If this button is pushed, the values of both sliders is pr... | true |
33f51afd4e3d5207a3c7ee1551f26d762a992658 | Jimut123/code-backup | /python_gui_tkinter/Tkinter/TkinterCourse/51_gridm.py | 1,569 | 4.28125 | 4 | '''
The first geometry manager of Tk had been pack. The algorithmic behaviour of pack is not easy to understand and it can be difficult to change an existing design. Grid was introduced in 1996 as an alternative to pack. Though grid is easier to learn and to use and produces nicer layouts, lots of developers keep using... | true |
de48fa8a397f50506934616e612f259f06c202a0 | shiyaowww/checkers | /coordinate.py | 2,720 | 4.25 | 4 | '''
Created by: Shiyao Wang
Time: Nov 12, 2020
Purpose: To represent a two-dimensional coordinate
'''
class Coordinate:
'''
Class -- Coordinate
Attributes:
x -- an integer or a float, the X coordinate
y -- an integer or a float, the Y coordinate
Methods:
increment_x, increment... | true |
fd511eaac15fb2beb7c8e25c1164d45f9c127f55 | Saurabh-sabby/Assignment-3 | /script_3/p2.py | 642 | 4.28125 | 4 | import math
class Circle:
def __init__(self,rd):
self.radius = rd
def circumference_of_circle(self):
return 2 * math.pi * self.radius
def compare_circles():
if no1>no2:
print("Circle 1 is bigger than Circle 2")
else:
print("Circle 2 is bigger th... | true |
65040babaab00e760593f1b471783edc29907db1 | ChuleHou/Python-Programming | /AnimalSubclass/animalGenerator.py | 1,236 | 4.40625 | 4 | import Animals
# Create a list for Animal objects
object_list = []
# Print a welcome message
print("Welcome to the animal generator!")
print("This program creates Animal objects")
while True:
# Ask the user for the animal's type
print("\nWould you like to create a mammal or bird? \n1. Mammal \n2. Bird")
... | true |
1970c693259781b0dfdf49667cad4ac4c2be9655 | Mponsubha/.guvi | /codekata/vow.py | 237 | 4.15625 | 4 | alpha=input()
alpha=alpha.lower()
if(alpha=='$' or alpha=='%' or alpha=='*' or alpha=='#'):
print("invalid")
elif(alpha=='a' or alpha=='e' or alpha=='i' or alpha=='o' or alpha=='u'):
print("Vowel")
else:
print("Consonant")
| false |
68e4ce941970536975cc767278d16fd2b4e46448 | moufil/opp-practice-2 | /2.py | 891 | 4.15625 | 4 | class TriangleChecker:
def __init__(self, a, b, c):
self.a, self.b, self.c = a, b, c
def is_triangle(self):
if self.a <= 0 or self.b <= 0 or self.c <= 0:
print("С отрицательными числами ничего не выйдет!")
else:
sides = sorted((self.a,... | false |
6cb1780c11f9e9ca1baa10d5db36ff9af957a93b | simsekonur/Python-exercises | /exercise/examples/num_bet.py | 224 | 4.1875 | 4 | # this function takes two integers and generates an ordered list of the numbers in between them
lst = []
def number_between(x,y):
for i in range (x+1,y):
lst.append(i)
return lst
print (number_between(3,10))
| true |
84d6a7438b540f210e1c46cb7d511e87e1886e59 | simsekonur/Python-exercises | /exercise/prime.py | 677 | 4.21875 | 4 | print ("********************")
print ("Is Prime Or Not?")
print ("To quit program , please press q ...")
print ("********************")
def IsPrime (number ):
for i in range (2,number):
if (number % i == 0 ):
return 0
return 1
while (True):
number = raw_input ("Enter the number :")
i... | true |
6dfdf91ffb157d4ee704d4ca63c9065a69cd9768 | simsekonur/Python-exercises | /exercise/examples/find_number.py | 357 | 4.125 | 4 | #This function takes a list and return the index of first number in it. if not found, returns -1.
def find_the_first_number (lst):
i=0
index = -1
while (i<len(lst)):
if (type(lst[i])==int or type(lst[i])==float):
index = i
break
i+=1
return index
print (find_the_f... | true |
61af9a4a4bc10f5302eccb7c6970ad4ae661cdc0 | simsekonur/Python-exercises | /exercise/examples/fibonacci_recursion.py | 265 | 4.3125 | 4 | print ("fibonacci sequence : 1 1 2 3 5 ...")
number = int (raw_input ("Enter the number:"))
def fibonacci (number):
if (number == 1 or number == 2):
return 1
else :
return fibonacci(number-1)+fibonacci (number-2)
print (fibonacci (number))
| false |
0e2c32c19aee4916d1d16505e2d32c7eae2ad2ca | simsekonur/Python-exercises | /breakAndContinue/break.py | 356 | 4.125 | 4 | print ("Before break")
for i in range (0,11):
print (i)
print ("After break")
for i in range (0,11):
if (i==5):
break
print (i)
lst =[1,2,3,4,5]
print ("The list before break")
for i in range (0,len (lst)):
print (lst[i])
print ("the list after break")
for i in range (0,len(lst)):
if (i==2):... | false |
174a2dd5e7d251704e7caa3f87637e100fe027ad | DrHIROMU/DataStructure | /Sorting/bubble_sort.py | 519 | 4.1875 | 4 | # Time Complexity: O(n^2)
def bubble_sort(numbers):
for i in range(len(numbers)-1, 0, -1):
for j in range(0, i, 1):
if numbers[j] > numbers[j+1]:
swap(numbers, j, j+1)
return numbers
def swap(num_array, index_a, index_b):
temp = num_array[index_a]
num_array[... | false |
1493c56771300b7432515b186cf62f80cd48bc13 | shyam192/project2 | /task2.py | 406 | 4.28125 | 4 | #printing positive number in a list
List1=[12,-7,5,64,-14] #input list
#printing positive numbers:
print("POSITIVE NUMBERS IN LIST 1 : ")
for number in List1:
if number>0: #COMPARING NUMBERS
print(number)
#list 2
List2=[12,14,-95,3] #input list
#printing positive numbers:
print("POSITI... | true |
c31706e51f25f392ea07fb6329e1dec5132de85f | ianmkinney/python-car | /car.py | 2,345 | 4.21875 | 4 | class car:
def __init__(self,company,car,mpg,gasTank):
self.company = company
self.car = car
self.mpg = mpg
self.gasTank = gasTank
self.milesDriven = 0
self.fill = 0
def takeTrip(self,miles):
if(miles > (self.fill * self.mpg)):
print("... | true |
b4fedf70cc76039262ac96905b6404e448a5dd7a | hussainrifat/Python-Practise | /if else1.py | 352 | 4.15625 | 4 | age=int(input("Enter your age: "))
if age>13 and age<18:
print("You are too young")
print("Why are you here?")
elif age>30 and age<40:
print("You are middle age army")
elif age==18:
print("Perfect! ")
elif age<13:
print("You are kid")
else:
print("Hi Grandpa!")
age=None
print("Value... | false |
d541951232c207a623de7e946bfaa931b5297f24 | priyankapatki/D04 | /HW04_ch08_ex05.py | 1,419 | 4.125 | 4 | #!/usr/bin/env python
# HW04_ch08_ex05
# Structure this script entirely on your own.
# See Chapter 8: Strings Exercise 5 for the task.
# Please do provide function calls that test/demonstrate your
# function.
###############################################################################
# Find the ord('a') and or... | true |
6e27999a74e944e99eb83262e45e538124292ace | madhank93/python_code_academy | /Find_odd_one_out.py | 1,139 | 4.53125 | 5 | '''Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given numbers differs
from the others. Bob observed that one number usually differs from the others in evenness. Help Bob — to check his answers,
he needs a program that among the given numbers finds one that is d... | true |
1ec2a390b5df4bccbcc4589fab4151d76144aa24 | chitradhak/Python-code | /exercises.py | 1,851 | 4.1875 | 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.
from datetime import date
'''
x = raw_input("Enter your name: ")
y = input("Enter your age: ")
z = input("Enter current age year: ")
actualyear = (... | true |
428d708c8394181c863374547677b57489fcc3d8 | Zoogster/python-class | /Lab 3/Lab03P3.py | 747 | 4.125 | 4 | delivery_type = input(
'Please enter the type of shipping you would like. For standard please enter put an "S". For express please enter an "E". ')
delivery_type = delivery_type.upper()
weight = float(input('Please enter weight of package in pounds: '))
if delivery_type == 'S':
if weight > 4 and weight <= 8:
... | true |
068b2ceee247c1790fdbdf9d3dc9464d58a30b36 | shreyasabharwal/Data-Structures-and-Algorithms | /Trees/4.4CheckBalanced.py | 1,242 | 4.1875 | 4 | '''4.4 Check Balanced: Implement a function to check if a binary tree is balanced. For the purposes of
this question, a balanced tree is defined to be a tree such that the heights of the two subtrees of any
node never differ by more than one.
'''
import math
from TreesBasicOperations import Node
def checkHei... | true |
c51551bad30d058c4c9836e68c24db8f06904fb1 | shreyasabharwal/Data-Structures-and-Algorithms | /Sorting/10.5SparseSearch.py | 1,896 | 4.21875 | 4 | '''10.5 Sparse Search: Given a sorted array of strings that is interspersed with empty strings, write a
method to find the location of a given string.
EXAMPLE
Input: ball, ['at', '', '', '', '', 'ball', '', '', 'car', '', '', 'dad', '', '']
Output: 4
'''
'''Approach: With empty strings interspersed, we... | true |
341087e1d6ee4615944a3875d945152fd72c50a0 | shreyasabharwal/Data-Structures-and-Algorithms | /Trees/104.maxDepthOfTree.py | 905 | 4.125 | 4 | '''104. Maximum Depth of Binary Tree
Given a binary 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.
Note: A leaf is a node with no children.
Example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
... | true |
1b553feabb6716007fff893cb537511e128cf37d | shreyasabharwal/Data-Structures-and-Algorithms | /Arrays and Strings/1.6stringCompression.py | 1,028 | 4.5625 | 5 |
'''
1.6 String Compression: Implement a method to perform basic string compression using the counts
of repeated characters. For example, the string aabcccccaaa would become a2blc5a3. If the
"compressed" string would not become smaller than the original string, your method should return
the original string.... | true |
74377e208b8fbcdeda031f15187c3cb0feabcbaa | shreyasabharwal/Data-Structures-and-Algorithms | /Arrays and Strings/CaesarCipher.py | 1,149 | 4.5625 | 5 | '''A Caesar Cipher is a simple and ancient encryption technique. It works by taking the a string of text and "rotating" each letter a fixed number of places down the alphabet. Thus if the "rotation" number is "3", then a A (the 1st letter) would become a D (the 4th), a B would become a E, and a Z would wrap around to b... | true |
9a608ee9f7632e06a129d6f8736588f52e539733 | shreyasabharwal/Data-Structures-and-Algorithms | /LinkedList/2.6Palindrome.py | 1,256 | 4.34375 | 4 | '''2.6 Palindrome: Implement a function to check if a linked list is a palindrome.
'''
# Node Insertion
from NodeInsertion import Node, LinkedList
def printElements(current):
"Print elements of the linked list"
while current:
print(current.data, end='\t')
current = current.next
def reverse(... | true |
fc9ca462b12da7ee144f8e2b62e950ce9d13f664 | skimaiyo16/andela-bc-5 | /listtest.py | 600 | 4.28125 | 4 | def find_missing(n, m):
''' find which elements are missing from a list '''
# check if both are empty
if m == [] and n == []:
return 0
#sort first to allow index comparison
m.sort()
n.sort()
if len(m) > len(n):
lst = [ x for x in m for y in n if x not in n]
return lst[0]
else... | false |
b06ceb8811ce508995dda589ff7e6c428a7fe79c | akmalist/Turtle_Racing_Game | /main.py | 1,508 | 4.21875 | 4 | from turtle import Turtle, Screen
import random
screen = Screen()
screen.setup(500, 400)
user_bet = screen.textinput(title = 'Make your bet', prompt='Which turtle will win the race? Enter Color: ')
colors = ['red', 'yellow', 'blue', 'green', 'purple', 'pink']
all_turtles = []
start = -70
for each_turtle in range(0... | true |
1ad193d77376d1506bf45c17890af109dff3020e | TheTonyKano/Side-Projects | /palindrome.py | 328 | 4.28125 | 4 | def isPalindrome(string):
revString = ''.join(reversed(string))
if string.replace(" ", "") == revString.replace(" ", "") and string.replace(" ", "") != "":
print("It's a Palindrome")
else:
print("It's not a Palindrome")
isPalindrome(str(input("Enter a word to see if it is a palindrome: ")).... | true |
b3fb1f82e9974d7729616adbdcb1c5d8b970b08e | TheTonyKano/Side-Projects | /improved_caesar_cypher.py | 1,226 | 4.125 | 4 | data = str(input("Enter text to be encrypted: "))
def encryptdata(string, shift):
code = ""
cypher = ''
for char in string:
code = ord(char) + shift
if char.isalpha():
if ord(char) <= 90 and ord(char) >= 65:
if code > 90 and code < 121:
phas... | false |
660bb04aed0a39f5188c37663f585c9c9059cc0a | trent-hodgins-01/ICS3U-Unit4-02-Python | /multiplication_loop.py | 978 | 4.53125 | 5 | # !/user/bin/env python3
# Created by Trent Hodgins
# Created on 09/29/2021
# This is the Multiplication Loop program
# The user enters in a positive integer
# The program tells the user the product the numbers from 1 to the number typed in
import math
def main():
# this function uses a while loop and calculate... | true |
0fd3628568032188eed79355e8af4a725e2a5aee | NickStrick/Code-Challenges | /lambda/LinkedListMap.py | 2,479 | 4.125 | 4 | # https://gist.github.com/seanchen1991/a151368df32b8e7ae6e7fde715e44b78
# reduce takes a data structure and either finds a key piece of data or
# be able to restructure the data structure
# 1. Reduce usually takes a linear data structure (99% we use reduce on an array)
# 2. Reduce "aggregates" all of the data in the... | true |
8988fd0eeeefa808228835e53227c88e312e2549 | OrlandoMatteo/ProgrammingForIot | /Training/Intro/solutions/exercise7.py | 631 | 4.125 | 4 | import random
if __name__=="__main__":
#Create a vector of random numbers (just to avoid to insert the numbers manually)
numbers=[random.randint(1,20) for i in range(16)]
#Set the value of the sum to 0 and max and min to the first number of the array
sum_of_n=0
l=len(numbers)
maximum=numbers[0]
minimum=numbers[0... | true |
91158a9ac64975fefee6ce03cc9744237e727cd3 | abrantesandreza/Exerc-cio-L-gica-de-Programa-o-Construir-triangulos-em-Python | /main.py | 744 | 4.15625 | 4 | print('Vamos representar um triângulo? ')
print('Obs: Nenhum valor pode ser 0, tá bom?')
lado1 = int(input('Escreva um valor para um lado do triângulo: '))
lado2 = int(input('Escreva um valor para um lado do triângulo: '))
lado3 = int(input('Escreva um valor para um lado do triângulo: '))
if (lado1 == lado2 == lad... | false |
4dc4228940deda83f59940020dfbd84b3848cc9a | mileidicabezas/python-scripting | /multiples-of-a-number/multiples_of_a_number.py | 485 | 4.15625 | 4 | #!/usr/bin/env python3
# permisopns to run the script: chmod u+x multiples_of_a_number.py
# run script: ./multiples_of_a_number.py
'''
Task:
Write a script that prints the multiples of 7 between 0 and 100.
Print one multiple per line and avoid printing any numbers that aren't multiples of 7.
Remember that 0 is als... | true |
256ed42c812e891d977a0fdcfc2f76427aea48db | pedroschmid/three-ways-external-merge-sort | /src/sorts.py | 1,185 | 4.125 | 4 | def merge_sort(array):
if len(array) > 1:
left_array = array[:len(array) // 2]
right_array = array[len(array) // 2:]
merge_sort(left_array)
merge_sort(right_array)
left_array_element = 0
right_array_element = 0
merged_array_element = 0
while... | false |
45ac177301fc72b07d41f833f7992aea1589f64c | expoashish/Data-structure-with-python | /bubble.py | 392 | 4.25 | 4 | # Bubble Sort is a simple algorithm which is used to sort a given
# set of n elements provided in form of an array with n number of
# elements. Bubble Sort compares all the element one by one and sort
# them based on their values.
data=[3,5,2,0,4]
for i in range(len(data)):
for j in range(0,len(data)-1):
if (dat... | true |
d17b8c9f674bf72ba05ffd3228b095a2f9b4625c | AaronEvanovich/practicepythonPractices | /reverse_word_order.py | 983 | 4.34375 | 4 | #====================
#Input a sentence and reverse it as the output
#====================
sentenceList = []
reverseSentenceList = []
#function to split a string into a list of words
def splitSentence(oriSentence):
global sentenceList
sentenceList = oriSentence.split(" ")
#function to reverse the list
def rev... | true |
3a3a089a365ddafaab4b342faca7d84bb601366f | ningmengpian/algorithm | /plus_one.py | 1,382 | 4.15625 | 4 | """
question:
给定一个由整数组成的非空数组所表示的非负整数,在该数的基础上加一。
最高位数字存放在数组的首位, 数组中每个元素只存储一个数字。
你可以假设除了整数 0 之外,这个整数不会以零开头。
链接:https://leetcode-cn.com/problems/plus-one
example:
输入: [1,2,3]
输出: [1,2,4]
解释: 输入数组表示数字 123。
输入:[999]
输出:[1000]
解释:输入数组表示数字 999。
"""
class Solution(object):
def plusOne(self, digits):
... | false |
2d4fea4fae212d82d9caae12fd0dfc3163c428d3 | ningmengpian/algorithm | /order_linked_list.py | 1,676 | 4.21875 | 4 | """
合并有序链表
question:
将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
examples:
示例:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
"""
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def create_link_list(list_number):
link_list = ListNode(0)
now_node = link_list
for temp... | false |
3da0e973cb58a2625b015ac9a0389f7a489326b8 | mitcns/python | /sequence-chapter6/uniFile.py | 419 | 4.125 | 4 | # coding=utf-8
# !/usr/bin/env python
'''
An example of reading & writing Unicode strings: Writes
a Unicode string to afile in utf-8 & reads it back in.
'''
CODEC = 'utf-8'
FILE = 'unicode.txt'
helloOut = u"你好,小马!\n"
bytesOut = helloOut.encode(CODEC)
f = open(FILE, "w")
f.write(bytesOut)
f.close()
f = open(F... | true |
335f2429dd0229d921ce8689ec009891c6860f68 | Hammad214508/Quarantine-Coding | /30-Day-LeetCoding-Challenge/September/Week2/9-CompareVersionNumbers.py | 2,254 | 4.25 | 4 | """
Given two version numbers, version1 and version2, compare them.
Version numbers consist of one or more revisions joined by a dot '.'. Each revision consists of digits and may contain leading zeros. Every revision contains at least one character. Revisions are 0-indexed from left to right, with the leftmost revisio... | true |
58c9a05a936f62ad8cf6d552880268738ee23019 | Hammad214508/Quarantine-Coding | /30-Day-LeetCoding-Challenge/August/Week1/1-DetectCapital.py | 1,462 | 4.34375 | 4 | """
Given a word, you need to judge whether the usage of capitals in it is right or not.
We define the usage of capitals in a word to be right when one of the following cases holds:
All letters in this word are capitals, like "USA".
All letters in this word are not capitals, like "leetcode".
Only the first letter in ... | true |
50fbe087f52cd05c43e5df3b8d30f989ea751870 | maverick317/python-projects | /Guess_The_Number.py | 719 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Dec 13 11:06:57 2019
@author: Maverick
"""
#Guess The Number
#import the necessary libraries
import random as rd
#generate random numbers
choice = rd.randint(1,10)
#ask the user for their input
number = int(input("Please enter a random number between 1 and 10: "))
if num... | true |
158eb7e628e612813380d86bac95160c7628eea1 | Jenychen1996/Basic-Python-FishC.com | /File/write_file.py | 398 | 4.1875 | 4 | #!/usr/local/bin/env python3
"""
1. Type the file name
2. Type the content
"""
def write_file(file_name):
f = open("file_name", 'w')
print("Please type the content, and type the ':w' to save and exit.")
while True:
content = input()
if content != ":w":
f.write('%s\n' % content)
else:
f.close()
... | true |
56b903d82840931f50aca4f2b2df7feef9e3c839 | LiliiaPav/learnPython | /Queue.py | 1,069 | 4.40625 | 4 | class Queue(object):
""" Queues are a fundamental computer science data structure.
A queue is basically like a line at Disneyland - you can add elements to a queue, and they maintain a specific order.
When you want to get something off the end of a queue, you get the item that has been in there the longest... | true |
4c87149ce7a6196a161e5e50240f39341518761b | momentum-cohort-2019-05/w2d1-house-hunting-radfordalex | /house_hunting.py | 564 | 4.25 | 4 | annual_salary = float(input("What is your annual salary?"))
portion_saved = float(input("What portion of your salary are you saving"))
total_cost = float(input("What is the cost of your house"))
monthly_salary = annual_salary/12
r = 0.04
current_savings = 0
months = 0
portion_down_payment = total_cost*0.25
while curre... | true |
a7f94c1f3c546691c9bd7706d694fe537b2a9a42 | python-code-assignment/Aastha-Vidushi | /recursive.py | 609 | 4.15625 | 4 | def removeNone(dictionary):
for k, v in dictionary.items():
if isinstance(v, dict):
removeNone(v)
elif (v==None):
dictionary.pop(k)
return dictionary
Dict = {
'Dict1': {'name': 'Ali', 'age': 19,'mob':123456},
'Dict2': {'name': 'Bob', 'age': ... | false |
537f22d10d805b252c0a8075902f84c337325d43 | JeniMercy/code | /Nov21Task3.py | 959 | 4.25 | 4 | #NOV-21
#Task3:
#collect one string from user, check whether the string is palindrome or not
a = str(input("Please enter your string : "))
reversed_string = a[::-1]
if a == reversed_string:
print(" The string {} is a palindrome".format(a))
else:
print("The string {} is not a palindrome".format(a))
... | false |
ab264107d88e3acbb02db59d459d21c008c9576e | JeniMercy/code | /November18-Tasks(Tuple).py | 1,336 | 4.15625 | 4 | #November Tasks-18
#Tuple
#Create two tuples (1,4,5,6,7,8) (5,6,7,8,9)
tuple1 = (1,4,5,6,7,8)
tuple2 = (5,6,7,8,9)
print(tuple1)
print(tuple2)
#Find the common elements between two tuples
#tuple1 = (1,4,5,6,7,8)
#tuple2 = (5,6,7,8,9)
set1 = set(tuple1)
set2 = set(tuple2)
set_inter = set1.intersection(set2... | true |
ded442ef12dcde0edd0429098374343ebb6af376 | JeniMercy/code | /Nov21task5.py | 891 | 4.3125 | 4 | #Nov21
#Task5:
#Get one string from user
#Find the middle letter
#find ascii value for the middle letter
#check whether ascii value is odd or even
a = input("Please enter your string : ")
middle_letter = len(a) // 2
print("The middle letter is {}".format(a[middle_letter]))
ascii_value = ord(a[middle_letter... | true |
01a97c6b3e39d19d0f22e1e213cfe8865f1a6566 | MagneeR/CursoLeonEoiPythonDjango | /python/7_listas.py | 1,210 | 4.53125 | 5 | """Ejemplos para trabajar con listas
ctrl+f2 sobre un nombre me deja cambiar ese nombre en todo el documento
"""
#En minuscula no se puede poner list porque es una palabra reservada de python
LIST = [1, 2, 3, 4, 5, "seis"] #Las listas son como arrays y en la consola se ve como array
print(LIST)
print(LIST[0]) #Asi mue... | false |
4d580db7d455b1a5b4e79049e765751ebf245695 | farah-ehsan-alyasari/Problem-Solving | /is_palindrome.py | 1,447 | 4.25 | 4 | '''
Scenario
Do you know what a palindrome is?
It's a word which look the same when read forward and backward. For example, "kayak" is a palindrome, while "loyal" is not.
Your task is to write a program which:
asks the user for some text;
checks whether the entered text is a palindrome, and prin... | true |
0ea06231dcc71065d5574582bb4c554b524595b2 | adamabusamra/python_prep | /python_prep/OOP/classes+instances.py | 1,146 | 4.34375 | 4 | # Defining a class
class Employee:
# This is a constructor in Python & it's called once an object is instantiated from this class.
def __init__(self,name,age):
# The self keyword is a refrence to (this) specific Object like this in other langs.
self.name = name
self.age = age
... | true |
df2e672c2797b2133e6272709c6bfa0c42d36575 | kdockman96/CS0008-f2016 | /Ch2-Ex3/ch2-ex3.py | 366 | 4.21875 | 4 | # This program calculates the number of acres in a tract of land
# Get the number of square meters in a tract of land
square_feet = int(input("How many square meters are in this tract of land? "))
# Calculate the size of the land in acres
land_size = square_feet/4046.8564224
# Display the result
print ("That's equal... | true |
df47e940dfc3b48f172226274ce226f37a1cb05e | kdockman96/CS0008-f2016 | /Ch3-Ex/ch3-ex2.py | 666 | 4.40625 | 4 | # Ask the user for the lengths and widths of two rectangles
length_1 = int(input('Enter the length of rectangle 1: '))
width_1 = int(input('Enter the width of rectangle 1: '))
length_2 = int(input('Enter the length of rectangle 2: '))
width_2 = int(input('Enter the width of rectangle 2: '))
# Display the formula for t... | true |
a2d1083c502e430a975a80190666b3ade660b45b | kdockman96/CS0008-f2016 | /Ch2-Ex7/ch2-ex7.py | 688 | 4.34375 | 4 | # Get the number of miles driven on last tank of gas
miles = input('How many miles did you drive on the last tank of gas? ')
# Get the number of the gallons of gas used
gallons = input('How many gallons did you use to fill the gas tank? ')
# Calculate MPG where MPG = miles driven/gallons of gas used
miles_per_gallon ... | true |
cf6920019e138bb580c52cd7aeb3db163dc204d8 | kdockman96/CS0008-f2016 | /ch4-ex/ch4-ex3.py | 800 | 4.25 | 4 | # Ask the user to enter the budget for the month
budget = float(input('Enter the amount budgeted for the month: '))
# Initialize an accumulator to keep a running total
total_expenses = 0
# Create a variable that will eventually terminate the loop
keep_going = 'y'
while keep_going == 'y':
expense = float(input('... | true |
ce33cd22609d9e91608005b2fd2ecb0ecfb6f13f | PoisonWater/class-work | /CSC1001/Integration.py | 1,269 | 4.1875 | 4 | from math import sin
from math import cos
from math import tan
try:
funcType = input('Which kind of function do you want to integrate? (sin, cos, tan)')
while funcType != 'sin' and funcType != 'cos' and funcType != 'tan':
print('Please input the correct form of function name!')
funcType = input... | true |
c90c584e96d35a73f6944c10400b132a1bc4bfc3 | Vykstorm/numpy-examples | /printing.py | 701 | 4.5625 | 5 |
'''
This example shows a few ways to print a numpy ndarray
'''
import numpy as np
if __name__ == '__main__':
# 1D arrays are printed like lists
print(np.arange(0, 9))
# 2D arrays are printed as matrices
print(np.arange(0, 9).reshape([3,3]))
# To print a 2D array as a flat vector...
print(np... | true |
f32428eb6c59c9e627541b0dc007c335aa3f8d22 | Vykstorm/numpy-examples | /creation.py | 2,184 | 4.21875 | 4 |
'''
This script shows different ways to create an numpy ndarray object
'''
import numpy as np
if __name__ == '__main__':
# Create an array from a iterable
np.array([3,1,4,1,5]) # dtype is guessed from value types
np.array([3,1,4,1,5], dtype=np.float64) # dtype can be specified as an argument.
# Yo... | true |
95a66e64fc30c2248c60e233b3b3b8b8feba5393 | fbreversg/checkio | /Dropbox/the-most-frequent-weekdays.py | 851 | 4.1875 | 4 | from datetime import datetime
from calendar import day_name
def most_frequent_days(year):
"""
List of most frequent days of the week in the given year
"""
firstweek = set(range(datetime(year, 1, 1).weekday(), 7)) # weekday 0..6
lastweek = set(range(datetime(year, 12, 31).isoweekda... | true |
e9ea7e76b99b19250e38dcd62a21ea64897c9ffd | blsoko/holbertonschool-higher_level_programming | /0x06-python-classes/5-square.py | 1,404 | 4.3125 | 4 | #!/usr/bin/python3
'''4-square.py: class square'''
class Square:
"""
Prototype of a square
"""
def __init__(self, size=0):
"""[summary]
Args:
size (int, optional): [size of square]. Defaults to 0.
""" '''Define Square instance in size'''
self.__... | true |
40bd91519789aa478b655afb491c5f327d127265 | blsoko/holbertonschool-higher_level_programming | /0x0B-python-input_output/100-append_after.py | 747 | 4.15625 | 4 | #!/usr/bin/python3
""" Write a function that inserts a line of text to a file
"""
def append_after(filename="", search_string="", new_string=""):
""" Write a function that inserts a line of text to a file
Args:
filename (str): [description]. Defaults to "".
search_string (str): [description].... | true |
42839964e03f3c355f7a040e86c3e12867921a41 | blsoko/holbertonschool-higher_level_programming | /0x0B-python-input_output/4-append_write.py | 399 | 4.125 | 4 | #!/usr/bin/python3
""" Append a file, create a file if it doesn't exist
"""
def append_write(filename="", text=""):
""" Append a file, create a file if it doesn't exist
Args:
filename (str): file read in mode utf-8. Defaults to "".
text (str): text to be written. Defaults to "".
"""
w... | true |
2c15008df2b04d7c930b3d188238cc9b13dc3e03 | jeffreybergman/sql | /sqle.py | 319 | 4.1875 | 4 | # SELECT statement
import sqlite3
# create the database connection
with sqlite3.connect("new.db") as connection:
# create the cursor
c = connection.cursor()
# use a for loop to iterate the database and print results
for row in c.execute("SELECT firstname, lastname FROM employees"):
print row | true |
3560f0d31ec285d5148ab4472369b9e061055f50 | micro-hawk/DevelopersHuntWork | /girish/vowels removing.py | 492 | 4.21875 | 4 | def removevowel(newstr,string):
vowels=('a','e','i','o','u','A','E','I','O','U')
for c in string:
if c in vowels:
newstr= newstr.replace(c,'')
print("the new string without the vowels is " + newstr)
return newstr
print("enter any string ou wish to remove the vowels of")
string=input... | false |
1ad8d767ef69651ffb1b51c9d7ee19552d369f23 | wafindotca/pythonToys | /leetcode/rotate_image.py | 1,152 | 4.125 | 4 | # https://leetcode.com/problems/rotate-image/
# You are given an n x n 2D matrix representing an image.
#
# Rotate the image by 90 degrees (clockwise).
#
# Follow up:
# Could you do this in-place?
# THOUGHTS: neither seems that bad.
# Let's start with not-in-place
class Solution(object):
def rotate(self, matri... | true |
93d120d51386895a7e431ced6e84cd670babec98 | Lennoard/ifpi-ads-algoritmos2020 | /Fabio02_Parte02a/q19_imc.py | 664 | 4.125 | 4 | #19. Leia a altura (em metros) e peso (em Kg) de uma pessoa, em seguida calcule o
# índice de massa corpórea (IMC = peso / altura2).
# Ao final, escreva se a pessoa está com peso normal (IMC abaixo de 25),
# obeso (IMC entre 25 e 30) ou obesidade mórbida (IMC acima de 30).
def calcular_imc(h, w):
return w / h**... | false |
cce78aed2ce9a025126ad53543a2fba8c64c5b9b | ssharm02/100_days_of_python | /dictionary comprehension/main.py | 1,779 | 4.1875 | 4 | import random
import pandas
# how to use dictionary comprehension
def dictionary_comprehension_test():
names = ["Sarthak", "Buddy", "Sakshi", "Bal", "Neelu", "Dofus"]
students_score = {student: random.randint(1, 101) for student in names}
print(students_score)
def dictionary_comprehension_if_condition()... | false |
4d73f8eaa9380e4a23e26a4bcb5ecd938ba3e8d0 | emon93/UCD-Work- | /PythonBasics.py | 819 | 4.1875 | 4 | # Create a variable savings
savings = 100
# Print out savings
print(savings)
# Create a variable savings
savings = 100
# Create a variable growth_multiplier
growth_multiplier = 1.1
# Calculate result
result = savings*growth_multiplier**7
# Print out result
print(result)
# Print type of variable
print(type(result)... | true |
ab86d1898cf79c6a8d5fc8b44c2f07df73fbc779 | nileshsinhasinha/Algorithms_and_Datastructure | /Heap.py | 2,426 | 4.125 | 4 | """Heap is a data structure which is almost complete tree (Either binary or ternary)
For Min heap implementation we can directly use heapq library of python
Here, we will be implementing Max Heap implementation"""
def max_heapify(Arr,node):
"""It will heapify the tree or subtree of which node will be provided"""
... | true |
e243ad75c09aba332864590b11bb21e91dd8ac0b | nileshsinhasinha/Algorithms_and_Datastructure | /TowerOfHanoi.py | 1,182 | 4.1875 | 4 | """Tower Of Hanoi:- Here we have to move n discs from source to target using intermediate.
Rules to follow:- 1st disc is lightest it can be put on any other disc anytime
Last disc is heaviest can be put on base only anytime"""
class toh:
movements=0
fn_c... | true |
03cda6541781523fa4e9b4dbed46f373741a80d2 | lxyshuai/target-at-offer | /68.树中连个节点的最低公共祖先.py | 1,861 | 4.21875 | 4 | # 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
"""
二叉树是BST
"""
class Solution(object):
def lowestCommonAncestor(self, root, p, q):
"""
... | false |
1ff42b25a1d604ddb6ec23bb4cb481eec20407b4 | EladioDeveloper/ArtificialIntelligence | /Practica 2/Part_I/1.1.py | 466 | 4.34375 | 4 | # 1. Write a Python program to count the number of characters (character frequency) in a string. Sample String : google.com'. Expected Result : {'g': 2, 'o': 3, 'l': 1, 'e': 1, '.': 1, 'c': 1, 'm': 1}
def character_frequency(input):
dictionary = {}
for n in input:
keys = dictionary.keys()
if n ... | true |
f28145e5e3bb9e068961908c68dd04d420bc8c6a | EladioDeveloper/ArtificialIntelligence | /Practica 2/Part_IV/4.47.py | 525 | 4.5 | 4 | # 47. Write a NumPy program to compute the inner product of vectors for 1-D arrays (without complex conjugation) and in higher dimension.
import numpy as np
a = np.array([1,2,5])
b = np.array([2,1,0])
print("Original 1-d arrays:")
print(a)
print(b)
result = np.inner(a, b)
print("Inner product of the said vectors:... | true |
8fa797f8fe4c032561eb59f7dca525824df51434 | oliver-hilder/CP1404_practicals | /prac_02/exceptions_demo.py | 1,023 | 4.5 | 4 | """
CP1404/CP5632 - Practical
Answer the following questions:
1. When will a ValueError occur?
A ValueError will occur if either the variable "numerator" or "denominator" receive input that is not an integer.
2. When will a ZeroDivisionError occur?
A ZeroDivisionError will occur if the user enters the value "0" into th... | true |
5bb9f5fbeee4b12f3601c61317387e13f62a0e90 | Ahmet-Kirmizi/Fibbonaci-sequence | /fibonacci.py | 695 | 4.40625 | 4 | # lets create a input variable that ask for the sequence
nth_term = int(input('please enter the number of sequences you want to see: '))
# count variable that will be used to break the while loop
count = 0
# everytime the loop starts over it will update count
# it will have 2 numbers
number1, number2 = 0, 1
... | true |
3053cfa29d6edc0db1f28bba3f84df8ca7cb1b82 | SIMELLI25/esercizi_python | /es7.py | 820 | 4.15625 | 4 | input("ES 7")
#Elenca proprietà e metodi della classe "Monociclo"
class Monociclo():
def __init__(self, template, color, price, max_speed):
self.template = template
self.color = color
self.price = price
self.max_speed = max_speed
def info(self):
print("Modello:", self.tem... | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.