blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
3867392dee2e78d71c9a8bf99e1372a46a0eb726 | beyondvalence/thinkpython | /tp.05.py | 1,537 | 4.15625 | 4 | #! Thinking Python, Chp05, conditionals and recursion
#5.1 modulus operator
print("5.1")
print("156%100=")
print(156%100)
#5.9 E2 stack diagrams for recursive functions
print("5.9 E2")
def do_n(f,n):
if n<=0:
return
f()
do_n(f, n-1)
def print_now(s='now'):
print(s)
do_n(print_now,6)
#5.11 keyboard input
prin... | true |
d59b573a9bc93897e130ad223c08f0b22b99bf0b | ankarn/groupIII_twintrons | /groupIII_3'_motif_search.py | 2,605 | 4.125 | 4 | ################################################################################
#
# Search for Group III twinton 3' motifs
# ______________________________________
#
# A program to to find 3' motifs for group III twintrons, given the external
# intron in FASTA format.
#
# ** Prog... | true |
ca55b480b5735b4bc0bcb9feb1bb810de93a1007 | andrewrisse/Exercises | /ArrayAndStringProblems/URLify.py | 1,727 | 4.1875 | 4 | """
URLify.py
Creator: Andrew Risse
Drew heavily from example 1.3 in "Cracking the Coding Interview" in attempt to understand and
write their Java version in Python.
This program replaces spaces in a string with '%20'.
Assumptions: the string has sufficient space at the end to hold the additional characters and ... | true |
ac4be20f003f5e94d72f2251cc53f7ef384d02f0 | chunhuayu/Python | /Crash Course/06. Operators.py | 616 | 4.3125 | 4 | # Multiply 10 with 5, and print the result.
>>> print(10*5)
# Divide 10 by 2, and print the result.
>>> print(10/2)
# Use the correct membership operator to check if "apple" is present in the fruits object.
>>> fruits = ["apple", "banana"]
>>> if "apple" in fruits:
print("Yes, apple is a fruit!")
# ... | true |
0d303b898e689b0460aecb8d16248106d3a0073e | chunhuayu/Python | /Crash Course/0702. Tuple.py | 2,436 | 4.78125 | 5 | # Tuple is immutable
# A tuple is a collection which is ordered and unchangeable. In Python tuples are written with round brackets.
# Create a Tuple:
>>> thistuple = ("apple", "banana", "cherry")
>>> print(thistuple)
('apple', 'banana', 'cherry')
# Access Tuple Items: You can access tuple items by referring to the ind... | true |
57c29ce26289441922f017c49a645f8cbe9ce17f | rajatpachauri/Python_Workspace | /While_loop/__init__.py | 260 | 4.25 | 4 | # while loop is mostly used for counting
condition = 1
while condition < 10:
print(condition)
condition += 1
# condition -= 1
# to create out own infinite loop
while True:
print('doing stuff')
# for breaking use control+c | true |
1aa840435f3eaabb240f81d193c62b3381f52110 | Aminaba123/LeetCode | /477 Total Hamming Distance.py | 1,306 | 4.1875 | 4 | #!/usr/bin/python3
"""
The Hamming distance between two integers is the number of positions at which
the corresponding bits are different.
Now your job is to find the total Hamming distance between all pairs of the
given numbers.
Example:
Input: 4, 14, 2
Output: 6
Explanation: In binary representation, the 4 is 010... | true |
0674b8d7de1b0a1f417b11be2eac016d459c8be5 | Aminaba123/LeetCode | /063 Unique Paths II.py | 1,948 | 4.1875 | 4 | """
Follow up for "Unique Paths":
Now consider if some obstacles are added to the grids. How many unique paths would there be?
An obstacle and empty space is marked as 1 and 0 respectively in the grid.
For example,
There is one obstacle in the middle of a 3x3 grid as illustrated below.
[
[0,0,0],
[0... | true |
a8e56295e5b3d81fc6b63eb549d4a4d4f51dd7ea | Aminaba123/LeetCode | /433 Minimum Genetic Mutation.py | 2,041 | 4.15625 | 4 | #!/usr/bin/python3
"""
A gene string can be represented by an 8-character long string, with choices
from "A", "C", "G", "T".
Suppose we need to investigate about a mutation (mutation from "start" to
"end"), where ONE mutation is defined as ONE single character changed in the
gene string.
For example, "AACCGGTT" -> "A... | true |
64ebeedfbf3d242316451493e0407916896c2f77 | Aminaba123/LeetCode | /403 Frog Jump.py | 2,164 | 4.28125 | 4 | """
A frog is crossing a river. The river is divided into x units and at each unit there may or may not exist a stone. The
frog can jump on a stone, but it must not jump into the water.
Given a list of stones' positions (in units) in sorted ascending order, determine if the frog is able to cross the river
by landing o... | true |
24ba1fb74133913ff4642b3168f44b775cf64b7c | Aminaba123/LeetCode | /384 Shuffle an Array.py | 1,372 | 4.28125 | 4 | """
Shuffle a set of numbers without duplicates.
Example:
// Init an array with set 1, 2, and 3.
int[] nums = {1,2,3};
Solution solution = new Solution(nums);
// Shuffle the array [1,2,3] and return its result. Any permutation of [1,2,3] must equally likely to be returned.
solution.shuffle();
// Resets the array ba... | true |
13684394a6e93a3c95c3c7916fcb88113a22e7a0 | Aminaba123/LeetCode | /088 Merge Sorted Array.py | 1,122 | 4.125 | 4 | """
Given two sorted integer arrays A and B, merge B into A as one sorted array.
Note:
You may assume that A has enough space (size that is greater or equal to m + n) to hold additional elements from B. The
number of elements initialized in A and B are m and n respectively.
"""
__author__ = 'Danyang'
class... | true |
36bd7b053f22dbde6145ee948b168bb114a1bcfe | Aminaba123/LeetCode | /225 Implement Stack using Queues.py | 1,673 | 4.28125 | 4 | """
Implement the following operations of a stack using queues.
push(x) -- Push element x onto stack.
pop() -- Removes the element on top of the stack.
top() -- Get the top element.
empty() -- Return whether the stack is empty.
Notes:
You must use only standard operations of a queue -- which means only push to back, p... | true |
85068b845fc62bc3ca6b9307072225de0f5d380f | Aminaba123/LeetCode | /353 Design Snake Game.py | 2,043 | 4.4375 | 4 | """
Design a Snake game that is played on a device with screen size = width x height.
"""
from collections import deque
__author__ = 'Daniel'
class SnakeGame(object):
def __init__(self, width, height, food):
"""
Initialize your data structure here.
@param width - screen width
@par... | true |
0f0c2b71165908b69143488b544ec20e7192961b | jiankangliu/baseOfPython | /PycharmProjects/02_Python官方文档/一、Python初步介绍/03_Python控制流结构/3.2判断结构.py | 1,030 | 4.125 | 4 | #3.2.1 if-else语句
#例1 求较大值
num1=eval(input("Enter the first number: "))
num2=eval(input("Enter the second number: "))
if num1>num2:
print("The larger number is:",num1)
else:
print("The larger number is: ",num2)
#3.2.2 if语句
firstNumber=eval(input("Enter the first number: "))
secondNumber=eval(input("E... | true |
5a391b6015b94af3800dba89cf6ed07e94d1f445 | daniyaniazi/Python | /COLLECTION MODULE.py | 2,510 | 4.25 | 4 | """COLLECTION MODULE IN PYTHON """
#LIST TUPLE DICTIONARY SET ARE CONTAINER
#PYTHON HAS COLLECTION MODULE FOR THE SHORTCOMMING OF DS
#PRVIDES ALTERNATIVES CONTAINER OF BUILTIN DATA TYPES
#specializex collection datatype
"""nametupele(), chainmap, deque, counter, orderedDict, defaultdic , UserDict, UserList,UserString""... | true |
aca916cd7150ccdc1dc3ddad48f5b41d53007f7f | StealthAdder/SuperBasics_Py | /functions.py | 2,101 | 4.46875 | 4 | # function is collection of code
# they together work to do a task
# they are called using a function call.
# to create a function we use a keyword called "def"
# --------------------------------------------------
# create a function.
def greetings():
print("Hello Dude!")
greetings() #calling the functi... | true |
89edd52a8e28902a6331f7d939e3a369e3e14e69 | Aravind-2001/python-task | /4.py | 242 | 4.15625 | 4 | #Python program to divided two numbers using function
def divided_num(a,b):
sum=a/b;
return sum;
num1=int(input("input the number one: "))
num2=int(input("input the number one :"))
print("The sum is",divided_num(num1,num2))
| true |
bf2443eb20578d0e4b5765abc5bd6d3c46fabdc6 | leelaram-j/pythonLearning | /com/test/package/lists.py | 1,231 | 4.125 | 4 | """
List in python
written inside []
sequence type, index based starts from 0
mutable
"""
a = [1, 2, 3, 4, 5]
print(a)
print(type(a))
print(a[1])
# array slicing
print("Slicing")
print(a[0:3])
print(a[2:])
print(a[:3])
print("-------------")
a = [1, "sample", True, 10.45, [1, 2, 3, 4]]
print(a)
print(type(a))
prin... | true |
934f9b2581ab5fa583aaf274d068448b9cc4f0de | sharpchris/coding352 | /8.py | 2,259 | 4.375 | 4 | # Codebites URL: https://codechalleng.es/bites/21/
cars = {
'Ford': ['Falcon', 'Focus', 'Festiva', 'Fairlane'],
'Holden': ['Commodore', 'Captiva', 'Barina', 'Trailblazer'],
'Nissan': ['Maxima', 'Pulsar', '350Z', 'Navara'],
'Honda': ['Civic', 'Accord', 'Odyssey', 'Jazz'],
'Jeep': ['Grand Cherokee', '... | true |
a017de5cb43b53b1f7c796ab015b91a68f09efdf | abhishekratnam/Datastructuresandalgorithmsinpython | /DataStructures and Algorithms/Recursion/Reverse.py | 445 | 4.1875 | 4 | def reverse(S, start, stop):
"""Reverse elements in emplicit slice S[start:stop]."""
if start < stop - 1:
S[start], S[stop-1] = S[stop - 1], S[start]
reverse(S, start+1, stop - 1)
def reverse_iterative(S):
"""Reverse elements in S using tail recursion"""
start,stop = 0,len... | true |
e03f40711cfe8a26b38de0c63faaee30e1b0e336 | pragatishendye/python-practicecode | /FahrenheitToCelsius.py | 338 | 4.40625 | 4 | """
This program prompts the user for a temperature in Fahrenheit and returns
the Celsius equivalent of it.
Created by Pragathi Shendye
"""
tempInFahrenheit = float(input('Enter a temperature in Fahrenheit:'))
tempInCelsius = (tempInFahrenheit - 32) * (5 / 9)
print('{} Fahrenheit = {:.2f} Celsius'.format(tempI... | true |
23a9baab1b0308bde129e6d01894f56ea79e3c64 | iresbaylor/codeDuplicationParser | /engine/utils/printing.py | 921 | 4.1875 | 4 | """Module containing methods for pretty-printing node trees."""
def print_node_list(node_list):
"""
Print a list of TreeNodes for debugging.
Arguments:
node_list (list[TreeNode]): a list of tree nodes
"""
for node in node_list:
if node.parent_index is None:
print_node... | true |
433453e34c036cf7b04079f06debd27ba3c31e69 | amarish-kumar/Practice | /coursera/coursera_data_structures_and_algorithms/course_1_algorithmic_toolbox/Week_4/binarysearch/binary_search.py | 2,180 | 4.15625 | 4 | #python3
'''Implementation of the binary search algoritm.
Input will contain two lines. First line will
have an integer n followed by n integers in
increasing order. Second line will have an
integer n again followed by n integers. For
each of the integers in the second line, you
have to perform bi... | true |
a58e51493d43ad0df89b3836366ef7b729223d57 | jnoriega3/lesson-code | /ch6/printTableFunctions.py | 2,680 | 4.59375 | 5 | # this is the printTable function
# parameter: tableData is a list of lists, each containing a word
# we are guaranteed that each list is the same length of words
# this function will print our table right-justified
def printTable( tableData ):
#in order to be able to right-justify each word, we'll... | true |
72218d09cd2c9a05bae3d9a2f22eccba436a554d | jnoriega3/lesson-code | /ch4/1-list-print.py | 638 | 4.46875 | 4 | #this defines a function with one parameter, 'theList'
def printList( theList ):
# this for loop iterates through each item in the list, except the last item
for i in range( len(theList)-1 ): #can you remember what this line does?
#this will add a comma after each list item
print( str(theList[i]... | true |
db8cc0d6b26b66a57b5db9b2478bedb0b463e5a6 | burakdemir1/BUS232-Spring-2021-Homeworks | /hw7.py | 407 | 4.21875 | 4 | names = ("Ross","Rachel","Chandler","Monica","Joey","Phoebe")
friends_list = set()
for name in names:
names_ = input(f'{name}, enter the names of the friends you invited: ')
name_list = names_.split()
for name in name_list:
friends_list.add(name)
print('This is final list of people invite... | true |
e0c8f24b3fd76f748f8aff3e31c04ec314ab6bba | skoolofcode/SKoolOfCode | /TrailBlazers/LiveClass/IntroToObjects_List.py | 741 | 4.53125 | 5 | #Lists - An unordered sequence of items
groceryList = ['Greens', 'Fruits', 'Milk']
print("My Grocery list is ", groceryList)
#You can iterate over lists. What's Iterate?
#Iterate means go one by one element traverssing the full list
#We may need to iterate the list to take some action on the given item
#e.g. what is ... | true |
19a636342dcb726c0a3c1ac89dab78319e4ca0c7 | skoolofcode/SKoolOfCode | /TrailBlazers/LiveClass/Files_Reading.py | 1,152 | 4.28125 | 4 | #Opening a file using the required permissions
f = open("data/drSeuss_green_eggs_n_ham.txt","r")
#Reading a file using readline() function
print("== Using for loop to read and print a file line by line ==")
#Default print parameters
for line in f:
print(line)
#Extra new lines after the every line. Why?
#Specify... | true |
01dc63ff29161279ab8cb689d375895180efc241 | skoolofcode/SKoolOfCode | /The Geeks/modules/IntroToModule.py | 780 | 4.15625 | 4 |
#introduction to Modules
#Let's create a module hello that has 2 function helloWorld() and helloRedmond()
#Diffirent ways of importing the module
#1. Import module as is with its name. Note the usage <module>.<function>
import hello
hello.helloIssaquah()
hello.helloRedmond()
hello.helloSeattle()
hello.helloBangal... | true |
fac14e0cfee5d22b65ca14fce29909c03c5a4f83 | skoolofcode/SKoolOfCode | /TrailBlazers/LiveClass/Class_3_2_Live.py | 820 | 4.15625 | 4 | #Print a decimal number as binary
#"{0:b}".format(number)
j = 45
print("The number j in decimal is ",j)
print("{0:b}".format(j))
#Use ord() to get Ascii codes for a given character
storeACharacter = 'a'
print("I am printing a character ", storeACharacter)
print("The ASCII code for a is ", ord(storeACharacter))
#Lets ... | true |
83e14b2a1a0b7d360c9ef3b979b5ac1c6fff630f | skoolofcode/SKoolOfCode | /CodeNinjas/SimplifiedHangMan.py | 1,441 | 4.46875 | 4 | #Simplified Hangman
#Present a word with only first 3 characters. Rest everything is masked
#The user would be asked to guess the word. He/She wins if the word is correctly guessed.
#A user get a total of 3 tires. At every try a new character is shown.
#Let's have a global word list.
worldList = ["batman","jumpsui... | true |
dbf8ea3834665ffc7df5953b5974455849501e16 | skoolofcode/SKoolOfCode | /The Geeks/list_methods.py | 1,042 | 4.59375 | 5 | # This file we'll be talking about Lists.
#Create a list
print("\n *** printing the list ***")
groceryList = ['Milk', 'Oranges', "Cookies", "Bread"]
print(groceryList)
#Append to the list. This also means add a item to the list
print("\n*** Add pumpkin to the list")
groceryList.append("pumpkin")
print(groceryList)
#... | true |
ac998b57fae60f1088db024c902ec8a9994b00d3 | skoolofcode/SKoolOfCode | /TrailBlazers/maanya/practice/caniguessyourage.py | 1,024 | 4.125 | 4 | def thecoolmathgame ():
print("Hello. I am going to guess your age today! I promise I will not cheat :)")
startnum = int(input("Pick a number from 1-10:"))
print("Now I will multiply your chosen number by 2.")
age = startnum * 2
print ("Now I will add 5 to the new number.")
age = age + 5
print("Now I will multip... | true |
315e47a3d80ac5835bb40dcc890b7bc924c08c1e | martyav/algoReview | /pythonSolutions/most_frequent_character.py | 878 | 4.1875 | 4 | # Frequency tables, frequency hashes, frequency dictionaries...
#
# Tomayto, tomahto, we're tracking a character alongside how many times it appears in a string.
#
# One small optimization is to update the most-frequently-seen character at the same time as
# we update the dictionary.
#
# Otherwise, we'd have to write ... | true |
07482b5f7f8b1ba25dbedc9a1f4398bb66ebd04a | SamuelNgundi/programming-challenges-with-python | /3.11. Book Club Points.py | 1,264 | 4.21875 | 4 | """
11. Book Club Points
Serendipity Booksellers has a book club that awards points to its customers
based on the number of books purchased each month.
The points are awarded as follows:
- If a customer purchases 0 books, he or she earns 0 points
- If a customer purchases 2 books, he or she earns 5 points
- If a cust... | true |
bb5d1cdeede1ec0a878ad5ee0f023e331f75d2dd | SamuelNgundi/programming-challenges-with-python | /3.2. Areas of Rectangles.py | 1,179 | 4.46875 | 4 | """
2. Areas of Rectangles
The area of a rectangle is the rectangles length times its width.
Write a program that asks for the length and width of two rectangles.
The program should tell the user which rectangle has the greater area,
or if the areas are the same.
Reference:
(1) Starting out with Python, Third Editi... | true |
afe32f4de9c73b431f8e20694a975a45ae993b34 | SamuelNgundi/programming-challenges-with-python | /3.1. Day of the Week.py | 1,136 | 4.46875 | 4 | """
1. Day of the Week
Write a program that asks the user for a number in the range of 1 through 7.
The program should display the corresponding day of the week, where 1 = Monday,
2 = Tuesday, 3 = Wednesday, 4 = Thursday, 5 = Friday, 6 = Saturday,
and 7 = Sunday.
The program should display an error message if the u... | true |
7e1205f5489688438da50bb992c737eaaf9504fa | rickydhanota/Powerset_py | /powerset_med.py | 1,006 | 4.15625 | 4 | #Powerset
#Write a function that takes in an array of unique integers and returns its powerset.
#The powerset P(X) of a set X is the set of all the subsets of X. for example, the powerset of [1, 2] is [[], [1], [2], [1, 2]]
#Note that the power sets do not need to be in any particular order
#Array = [1, 2, 3]
#[[], [... | true |
9b010ff1877e1ef42db1fe2f8d630dff72b2c544 | JakobHavtorn/algorithms-and-data-structures | /data_structures/stack.py | 1,975 | 4.1875 | 4 | class Stack(object):
def __init__(self, max_size):
"""Initializes a Stack with a specified maximum size.
A Stack incorporates the LIFO (Last In First Out) principle.
Args:
max_size (int): The maximum size of the Stack.
"""
assert type(max_size) is int and max_si... | true |
0cac7a90f5b2e66b12400a09cb98a0028eda2883 | Utkarsh016/fsdk2019 | /day4/code/latline.py | 426 | 4.15625 | 4 | """
Code Challenge
Name:
Last Line
Filename:
lastline.py
Problem Statement:
Ask the user for the name of a text file.
Display the final line of that file.
Think of ways in which you can solve this problem,
and how it might relate to your daily work with Python.
"""
file_name=input("ent... | true |
8662bda8ca8c11a857c90048e588861d7eb475c7 | rshandilya/IoT | /Codes/prac2d.py | 1,523 | 4.3125 | 4 | ############# EXPERIMENT 2.D ###################
# Area of a given shape(rectangle, triangle, and circle) reading shape and
# appropriate values from standard input.
import math
import argparse
import sys
def rectangle(x,y):
"""
calculate area and perimeter
input: length, width
output: dict - area, p... | true |
3d120963e6082fc867cb0b2266e0f4aa63ff458e | wensheng/tools | /r2c/r2c.py | 1,795 | 4.25 | 4 | #!/bin/env python
"""
Author: Wensheng Wang (http://wensheng.com/)
license: WTFPL
This program change change rows to columns in a ASCII text file.
for example:
-----------
hello
world
!
-----------
will be converted to:
-----------
h w!
e o
l r
l l
o d
-----------
If you specify '-b', vertical bars will be added to... | true |
0b44b64de6e6b1c1e58b40b4d793d4e5bb14cbc2 | zertrin/zkpytb | /zkpytb/priorityqueue.py | 2,082 | 4.25 | 4 | """
An implementation of a priority queue based on heapq and
https://docs.python.org/3/library/heapq.html#priority-queue-implementation-notes
Author: Marc Gallet
Date: 2018-01
"""
import heapq
import itertools
class EmptyQueueError(Exception):
pass
class PriorityQueue:
"""Based on https://docs.python.org/... | true |
ccb58c3b3faee4d0b2a14e600c2881a3d5ecb362 | atravanam-git/Python | /DataStructures/tuplesCodeDemo_1.py | 1,133 | 4.6875 | 5 | """tuples have the same properties like list:
#==========================================================================
# 1. They allow duplicate values
# 2. They allow heterogeneous values
# 3. They preserve insertion order
# 4. But they are IMMUTABLE
# 5. tuple objects can be used as keys in Dictionaries
#=========... | true |
0160126d1a2e614c95b844adb1524a6982f50493 | atravanam-git/Python | /FunctionsDemo/globalvarDemo.py | 902 | 4.53125 | 5 | """
#==========================================================================
# 1. global vs local variables in functions
# 2. returning multiple values
# 3. positional args vs keyword args
# 4. var-args, variable length arguments
# 5. kwargs - keyword arguments
#======================================================... | true |
964c6e0588f5e3ca4aabb1cd861357f6d935a595 | cuongdv1/Practice-Python | /Python3/database/create_roster_db.py | 2,652 | 4.125 | 4 | """
Create a SQLite database using the data available in json stored locally.
json file contains the users, courses and the roles of the users.
"""
# Import required modules
import json # to parse json
import sqlite3 # to create sqlite db
import sys # to get coomand line arguments
# G... | true |
b0436a9cd1ab679ac92b3fa3bd75786a3cb52067 | spectrum556/playground | /src/homework_1_additional/h_add.7.py | 566 | 4.25 | 4 | __author__ = 'Ihor'
month_num = int(input('enter the number of month\n'))
def what_season(month_num):
if month_num == 1 or month_num == 2 or month_num == 12:
return 'Winter'
elif month_num == 3 or month_num == 4 or month_num == 5:
return 'Spring'
elif month_num == 6 or month_num == 7 or m... | true |
c1e0a3c70cfd90f4753bc9b46c101c2e7ad1227d | wardk6907/CTI110 | /P5T2_FeetToInches_KaylaWard.py | 520 | 4.3125 | 4 | # Feet to Inches
# 1 Oct 2018
# CTI-110 P5T2_FeetToInches
# Kayla Ward
#
# Constant for the number of inches per foot.
inches_per_foot = 12
# Main Function
def main():
# Get a number of feet from the user.
feet = int(input("Enter a number of feet: "))
# Convert that to inches.
print(f... | true |
55accbf96df3236d8b55ada121259a0cf95daf99 | PraveenMut/quick-sort | /quick-sort.py | 783 | 4.15625 | 4 | # QuickSort in Python using O(n) space
# tester array
arr = [7,6,5,4,3,2,1,0]
# partition (pivot) procedure
def partition(arr, start, end):
pivot = arr[end]
partitionIndex = start
i = start
while i < end:
if arr[i] <= pivot:
arr[i],arr[partitionIndex] = arr[partitionIndex],arr[i]
partitionInd... | true |
ed4bf2d14601305473a0e708b7933c28c679aed5 | bscott110/mthree_Pythonpractice | /BlakeScott_Mod2_TextCount.py | 1,366 | 4.3125 | 4 | import string
from string import punctuation
s = """Imagine a vast sheet of paper on which straight Lines, Triangles, Squares, Pentagons, Hexagons, and other figures,
instead of remaining fixed in their places, move freely about, on or in the surface,
but without the power of rising above or sinking below it, v... | true |
b54d309379486f336fcd189b81a9a1df5fba77d0 | AnirbanMukherjeeXD/Explore-ML-Materials | /numpy_exercise.py | 2,818 | 4.28125 | 4 | # Student version : https://tinyurl.com/numpylevel1-280919
# Use the numpy library
import numpy as np
def prepare_inputs(inputs):
# TODO: create a 2-dimensional ndarray from the given 1-dimensional list;
# assign it to input_array
n = len(inputs)
input_array = np.array(inputs).reshape(1,n)
... | true |
f7754142cebe7e721ca0cd13187d4025a625cdba | cbira353/buildit-arch | /_site/writer1.py | 445 | 4.15625 | 4 | import csv
from student import Student
students = []
for i in range(3):
print('name:', end='')
name = input()
print('dorm:', end='')
dorm = input()
students.append(Student(name, dorm))
for student in students:
print("{} is in {}.".format(student.name, student.dorm))
file =open("students.cs... | true |
94908555a5067b29f51bc69eb397cb1f3aace887 | onizenso/College | /classes/cs350/wang/Code/Python/coroutines.py | 1,990 | 4.5 | 4 | #!/usr/bin/env python
# demonstrate coroutines in Python
# coroutines require python 2.5
"""
this simple example is a scheduler for walking dogs
the scheduler subroutine and main() act as coroutines
yield hands off control, next() and send() resumes control
"""
def printdog(name): # a... | true |
2696488fbf8a0c27b5c410bdca8fab666eeaa213 | BeniyamL/alx-higher_level_programming | /0x0A-python-inheritance/9-rectangle.py | 1,166 | 4.34375 | 4 | #!/usr/bin/python3
"""
class definition of Rectangle
"""
BaseGeometry = __import__('7-base_geometry').BaseGeometry
class Rectangle(BaseGeometry):
"""
class implementation for rectangle
"""
def __init__(self, width, height):
"""initialization of rectangle class
Arguments:
w... | true |
37f0162910ed4541fbad07ba16b71d71b406449f | BeniyamL/alx-higher_level_programming | /0x03-python-data_structures/2-replace_in_list.py | 384 | 4.3125 | 4 | #!/usr/bin/python3
def replace_in_list(my_list, idx, element):
"""
replace_in_list - replace an element of a list
@my_list: the given list
@idx: the given index
@element: element to be replaced
@Return : the replaced element
"""
if idx < 0 or idx >= len(my_list):
return my_list
... | true |
a7ce1f8eca0bed05c35f6cbaa0671ec1febea9df | BeniyamL/alx-higher_level_programming | /0x04-python-more_data_structures/6-print_sorted_dictionary.py | 311 | 4.40625 | 4 | #!/usr/bin/python3
def print_sorted_dictionary(a_dictionary):
"""function to sort a dictionary
Arguments:
a_dictionary: the given dictionary
Returns:
nothing
"""
sorted_dict = sorted(a_dictionary.items())
for k, v in sorted_dict:
print("{0}: {1}".format(k, v))
| true |
0497d2f931697ad17a338967d629b2c430ece31b | BeniyamL/alx-higher_level_programming | /0x0B-python-input_output/100-append_after.py | 660 | 4.28125 | 4 | #!/usr/bin/python3
""" function defintion for append_after
"""
def append_after(filename="", search_string="", new_string=""):
""" function to write a text after search string
Arguments:
filename: the name of the file
search_string: the text to be searched
new_string: the string to be... | true |
ee769eb6ad867b1e9b7cb2462c2b48ac2abaf5b8 | BeniyamL/alx-higher_level_programming | /0x07-python-test_driven_development/4-print_square.py | 485 | 4.46875 | 4 | #!/usr/bin/python3
""" print_square function """
def print_square(size):
""" function to print a square of a given size
Arguments:
size: the size of the square
Returns:
nothing
"""
if type(size) is not int:
raise TypeError("size must be an integer")
if type(size) is in... | true |
2d55b3451ad2d1d344cb614b0b8ab8eb085fb125 | JanhaviMhatre01/pythonprojects | /flipcoin.py | 618 | 4.375 | 4 | '''
/**********************************************************************************
* Purpose: Flip Coin and print percentage of Heads and Tails
* logic : take user input for how many times user want to flip coin and generate head or
* tail randomly and then calculate percentage for head and tail
*
* @author : Janh... | true |
8cb108ab7d77ee8f7d7e44b68b2d0b0fdd77849b | rodrigo-meyer/python_exercises | /odd_numbers_selection.py | 340 | 4.3125 | 4 | # A program that calculates the sum between all the odd numbers
# that are multiples of 3 and that are in the range of 1 to 500.
# Variables.
adding = 0
counter = 0
for c in range(1, 501, 2):
if c % 3 == 0:
counter = counter + 1
adding = adding + c
print('The total sum of {} values is {}'.forma... | true |
34c3bec34c7d4c18596381f3ac1c7164a183091f | gulnarap1/Python_Task | /Task3_allincluded.py | 2,822 | 4.1875 | 4 | #Question 1
# Create a list of the 10 elements of four different types of Data Types like int, string,
#complex, and float.
c=[2, 6, 2+4j, 3.67, "Dear Client", 9, 7.9, "Hey!", 4-3j, 10]
print(c)
#Question 2
#Create a list of size 5 and execute the slicing structure
my_list=[10, 20, ["It is me!"], 40, 50]
#Slicing
S... | true |
46f0f7ed004db78260c547f99a3371bb64ce6b08 | MemeMasterJeff/CP1-programs | /9-8-payroll-21.py | 2,572 | 4.125 | 4 | #William Wang & Sophia Hayes
#9-8-21
#calculates payroll for each employee after a week
#defins the employee class
try:
class employee:
def __init__(self, name, pay):
self.name = name
self.pay = pay
#inputted/calculated values
self.rate = float(inp... | true |
b7c53f9f71b18e7b850c9d6327507cd6590a43e3 | gomezquinteroD/GWC2019 | /Python/survey.py | 557 | 4.1875 | 4 | #create a dictionary
answers = {}
# Create a list of survey questions and a list of related keys that will be used when storing survey results.
survey = [
"What is your name?",
"How old are you?",
"What is your hometown?",
"What is your date of birth? (DD/MM/YYYY)"]
keys = ["name", "age", "hometown", "... | true |
4e808368dcb9f4e791aca828f31a17b47c6947dc | macrespo42/Bootcamp_42AI | /day00/ex03/count.py | 1,009 | 4.375 | 4 | import sys
import string
def text_analyzer(text=None):
"""
This functions count numbers of upper/lower letters, punctuation spaces
and letters in a string
"""
upper_letters = 0
lower_letters = 0
punctuation = 0
spaces = 0
text_len = 0
if (text == None):
print("Wh... | true |
26d14c6b1786baf307400f126ca9c81f183d0aa3 | AndrewBatty/Selections | /Selection_development_exercise_2.py | 368 | 4.125 | 4 | # Andrew Batty
# Selection exercise:
# Development Exercise 2:
# 06/102014
temperature = int(input("Please enter the temperature of water in a container in degrees centigrade: "))
if temperature <= 0:
print("The water is frozen.")
elif temperature >=100:
print("The water is boiling.")
else:
pr... | true |
3b4608f02475a5cb37397511b3fa5bad4c4007e2 | earth25559/Swift-Dynamic-Test | /Number_3.py | 530 | 4.1875 | 4 | test_array = [-2, -3, 4, -6, 1, 2, 1, 10, 3, 5, 6, 4]
def get_index(max_val):
for index, value in enumerate(test_array):
if(value == max_val):
return index
def find_index_in_array(arr):
max_value = arr[0]
for value in arr:
if value > max_value:
max_value = value
... | true |
e4ad61b609bed028b402265b224db05ceef7e2de | itaditya/Python | /Maths/toPostfixConv.py | 937 | 4.125 | 4 | from stack import Stack
def prec(operator):
if(operator == '^'):
return 3
elif(operator == '*' or operator == '/'):
return 2
elif(operator == '+' or operator == '-'):
return 1
else:
return -1
# print("Not a valid operator")
def postfixConv():
s = Stack()
e... | true |
275fe7b79c7c091237ce170cb043b4983a1fc1b2 | SweLinHtun15/GitFinalTest | /Sets&Dictionaries.py | 1,520 | 4.1875 | 4 | #Sets
#include a data type for sets
#Curly braces on the set() function can be used create sets.
basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
print(basket)
#Demonstrates set operations on unique letters from two words
a = set('abracadabra')
b = set('alacazm')
a # unique letter in a
a - b ... | true |
885d43c1619d5ddd8166a60492eb74f026778c5f | Candy-Robot/python | /python编程从入门到实践课后习题/第七章、用户输入与循环/while.py | 1,683 | 4.15625 | 4 | """
prompt = "\nwhat Pizza ingredients do you want: "
prompt += "\n(Enter 'quit' when you are finished) "
while True:
order = input(prompt)
if order == 'quit':
break
print("we will add this "+order+" for you")
prompt = "\nwhat Pizza ingredients do you want: "
prompt += "\n(Enter 'quit' when you ... | true |
07df07e0d977f286a3cb28c187f5a4adbbd2fd12 | samyhkim/algorithms | /56 - merge intervals.py | 977 | 4.25 | 4 | '''
sort by start times first
if one interval's end is less than other interval's start --> no overlap
[1, 3]: ___
[6, 9]: _____
if one interval's end is greater than other interval's started --> overlap
[1, 3]: ___
[2, 6]: _____
'''
def merge(intervals):
merged = []
intervals.sort(key=lambda i: i[0]) ... | true |
79ca667df5a747c3926ca8806022df645789d6d5 | abisha22/S1-A-Abisha-Accamma-vinod | /Programming Lab/27-01-21/prgm4.py | 437 | 4.25 | 4 | Python 3.9.1 (tags/v3.9.1:1e5d33e, Dec 7 2020, 17:08:21) [MSC v.1927 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> def word_count(str):
counts=dict()
words=str.split()
for word in words:
if word in counts:
counts[word]+=1
else:
counts[word]=... | true |
a00231b5aaa06630c3237083ca1650384ce7d71b | FJLRivera86/Python | /Dictionary.py | 1,118 | 4.53125 | 5 | #DICTIONARY {}: Data structure Like Tuple or List
#It's possible save elements,list or tuples in a dictionary
firstDictionary = {"Germany":"Berlin", "France":"Paris", "England":"London", "Spain":"Madrid"}
#To print a value, It's necessary say its KEY
print(firstDictionary)
print(firstDictionary["England"])
#ADD eleme... | true |
2d042a110b5642719a60a1d5aedc4528bb40cb86 | momentum-cohort-2019-05/w2d1-house-hunting-redkatyusha | /house_hunting.py | 754 | 4.1875 | 4 | portion_down_payment = .25
current_savings = 0
r = .04
months = 0
annual_salary_as_str = input("Enter your annual salary: ")
portion_saved_as_str = input(
"Enter the percent of your salary to save, as a decimal: ")
total_cost_as_str = input("Enter the cost of your dream home: ")
annual_salary = int(annual_salary_a... | true |
f2ce62028c31efdc396f3209e1c30681daa87c17 | pmxad8/cla_python_2020-21 | /test_files/test_1.py | 769 | 4.21875 | 4 | ################### code to plot some Gaussians ####################################
#### import libraries ####
import math
import numpy as np #import numerical library
import matplotlib.pyplot as plt #allow plotting
n = 101 # number of points
xx = np.linspace(-10,10,n) #vector of linearly spaced points
s = 0.5,1,1.5... | true |
7deff2841c1b9164ff335a4b1cb11c3266482a00 | SuryaDhole/tsf_grip21 | /main.py | 2,683 | 4.125 | 4 | # Author: Surya Dhole
# Technical TASK 1: Prediction using Supervised ML (Level - Beginner)
# Task Description: in this task, we will predict the percentage of marks that a student
# is expected to score based upon the number of hours
# they studied. This is a simple linear regression task as it involves just two var... | true |
eeb9ffe5b8ebe9beb9eda161b15b61ccea90ba9a | RezaZandi/Bank-App-Python | /old_code/switch_satements.py | 758 | 4.15625 | 4 |
"""
def main():
print("hi")
main_console = ("\nSelect an option to begin:")
main_console += ("\nEnter 0 to Create a new account")
main_console += ('\nEnter 1 to Deposit')
main_console += ('\nEnter 2 to Withdraw')
main_console += ('\n What would you like to do?: ')
while True:
user_option = int(i... | true |
382fbdd4d1b95633025b9f2951ddaa904a1727f1 | AdaniKamal/PythonDay | /Day2/Tuple.py | 2,762 | 4.53125 | 5 | #Tuple
#1
#Create a Tuple
# Set the tuples
weekdays = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday")
weekend = "Saturday", "Sunday"
# Print the tuples
print('-------------------------EX1---------------------------------')
print(weekdays)
print(weekend)
#2
#Single Item Tuples
a = ("Cat")
b = ("Cat",)
print('... | true |
9ffe03358e681158af1452776150deb8057eaa29 | violetscribbles/Learn-Python-3-the-Hard-Way-Personal-Exercises | /Exercises 1 - 10/ex9.py | 791 | 4.28125 | 4 | # Here's some new strange stuff, remember type it exactly.
# Defines 'days' variable as a string
days = "Mon Tue Wed Thu Fri Sat Sun"
# Defines 'months' variable as a string. Each month is preceded by \n, which
# is an escape character that tells python to create a new line before the
# text.
months = "\nJan\nF... | true |
974f629117846daae4de8b0e22b1d68407763078 | study-material-stuff/Study | /Study/Python/Assignments/Assignment 8/Assignment8_5.py | 570 | 4.28125 | 4 | #5.Design python application which contains two threads named as thread1 and thread2.
#Thread1 display 1 to 50 on screen and thread2 display 50 to 1 in reverse order on
#screen. After execution of thread1 gets completed then schedule thread2.
import threading;
def DispNumbers():
for no in range(1,51):
prin... | true |
2fb056ddefd2368f9947f213e92627b9e09071e1 | study-material-stuff/Study | /Study/Python/Assignments/Assignment 4/Assignment4_1.py | 238 | 4.28125 | 4 | #1.Write a program which contains one lambda function which accepts one parameter and return
#power of two.
powerof2 = lambda num : num * num;
num = int(input("Enter the number :"));
print("power of the number is ",powerof2(num)); | true |
d023f2fe5bfb44a3ca32176ad557542eeaf0883b | Devil-Rick/Advance-Task-6 | /Inner and Outer.py | 506 | 4.1875 | 4 | """
Task
You are given two arrays: A and B .
Your task is to compute their inner and outer product.
Input Format
The first line contains the space separated elements of array A .
The second line contains the space separated elements of array B .
Output Format
First, print the inner product.
Second, p... | true |
e9ff6b17552a2cc278d5817ce0ced6ef730cc144 | ilakya-selvarajan/Python-programming | /mystuff/4prog2.py | 353 | 4.21875 | 4 | #a program that queries the user for number, and proceeds to output whether the number is an even or an odd number.
number=1
while number!=0:
number = input("Enter a number or a zero to quit:")
if number%2==0 and number!=0:
print "That's an even number"
continue
if number%2==1:
print "That's an odd number"
... | true |
876eb77d4a81863b5d478f37827c0298a4270cf2 | ilakya-selvarajan/Python-programming | /mystuff/7prog6.py | 440 | 4.125 | 4 | #A function which gets as an argument a list of number tuples, and sorts the list into increasing order.
def sortList(tupleList):
for i in range( 0,len(tupleList) ):
for j in range(i+1, len(tupleList) ):
if tupleList[j][0]*tupleList[j][1]<tupleList[i][0]*tupleList[i][1]:
temp=tupleList[j]
tupleList[j]=t... | true |
eee40d974a515868c2db25c959e1cfa303002d00 | ilakya-selvarajan/Python-programming | /mystuff/8prog4.py | 433 | 4.21875 | 4 | # A function to find min, max and average value
from __future__ import division
def minMaxAvg(dict):
sum=0
myTuple=()
myValues= dict.values() #extracting the values
for values in myValues:
sum+=values
avg=sum/len(myValues) #Calculating the average
myTuple=(min(myValues),max(myValues),avg) #Return... | true |
68b01adeba8e433530175f0c39a80c5c336d1ce3 | thinboy92/HitmanFoo | /main.py | 2,562 | 4.21875 | 4 | ### Animal is-a object (yes, sort of confusing) look at the extra credit
class animal(object):
def __init__(self, type):
self.type = type
def fly(self):
print "This %s can fly" %(self.type)
## Dog is-a animal
class Dog(animal):
def __init__(self, name):
# class Doh has-a __init__ that accepts self an... | true |
03bc0cf52a337355dc9d829995465da3778f8531 | bulsaraharshil/MyPyPractice_W3 | /class.py | 1,071 | 4.40625 | 4 | class MyClass:
x = 5
print(MyClass)
#Create an object named p1, and print the value of x
class MyClass:
x=5
p1=MyClass()
print(p1.x)
#Create a class named Person, use the __init__() function to assign values for name and age
class Person:
def __init__(self,name,age):
self.name = name
self.age = ... | true |
1f468a2055ef8548a517fb5333f574737a2da217 | bulsaraharshil/MyPyPractice_W3 | /lambda.py | 768 | 4.5 | 4 | #lambda arguments : expression
#A lambda function that adds 10 to the number passed in as an argument, and print the result
x = lambda x:x+5
print(x(5))
#A lambda function that multiplies argument a with argument b and print the result
x = lambda a,b:a*b
print(x(5,6))
#A lambda function that sums argument a, b, and c... | true |
36b2d60352a9e55abb53d30f25e98319383dadc0 | dindamazeda/intro-to-python | /lesson3/exercise/7.element-non-grata.py | 542 | 4.28125 | 4 | # We have a list of sweets. Write a program that will ask the user which is his least favourite sweet and then remove that sweet from the list
### example ###
# sweets = ['jafa', 'bananica', 'rum-kasato', 'plazma', 'mars', 'bananica']
# program: Which one is your least favourite?
# korisnik: bananica
# program: ['jafa'... | true |
05cb1521168d0320f080cd8c25137ea9ef6e91b9 | dindamazeda/intro-to-python | /lesson2/exercises/3.number-guessing.py | 821 | 4.1875 | 4 | # Create list of numbers from 0 to 10 but with a random order (import random - see random module and usage)
# Go through the list and on every iteration as a user to guess a number between 0 and 10
# At end the program needs to print how many times the user had correct and incorrect guesses
# random_numbers = [5, 1, 3,... | true |
227d3c1780cca1ea0979d759c9a383fcdafb2314 | dindamazeda/intro-to-python | /lesson1/exercises/6.more-loops_dm.py | 612 | 4.3125 | 4 | # write a loop that will sum up all numbers from 1 to 100 and print out the result
### example ###
# expected result -> 5050
sum = 0
for numbers in range(1, 101):
sum = sum + numbers
print(sum)
# with the help of for loop triple each number from this list and print out the result
numbers = [5, 25, 66, 3, 100, 34]... | true |
bb941f4da9976abb554a43fe2d348ec956587cf1 | micalon1/small_tasks | /part5.py | 760 | 4.125 | 4 | shape = input("Enter a shape: ")
s = "square"
r = "rectangle"
c = "circle"
if shape == s:
l = int(input("What is the length of the square? "))
print("The area of the square is {}.". format(l**2))
elif shape == r:
h = int(input("What is the height of the rectangle? "))
w = int(input("What is the ... | true |
7bd385f1465918ac1c73311062647516a0d8ce74 | ritesh2k/python_basics | /fibonacci.py | 328 | 4.3125 | 4 | def fibonacci(num):
if num==0: return 0
elif num==1: return 1
else:
return fibonacci(num-1)+fibonacci(num-2) #using recursion to generate the fibonacci series
num=int(input('How many fibonacci numbers do you want? \n'))
print('Fibonacci numbers are :\n')
for i in range(num):
print(fibonacci(i) , end=' ')
p... | true |
7c3e9c6db39509af1c38818f60a5b9c9697697c4 | ritesh2k/python_basics | /sentence_capitalization.py | 429 | 4.3125 | 4 | def capitalization(str):
str=str.strip()
cap=''
for i in range(len(str)):
if i==0 or str[i-1]==' ':cap=cap+str[i].upper() #checking for the space and the first char of the sentence
else: cap=cap+str[i] #capitalizing the character after space
#cap =[words[0].upper()+words[1:]]
print ('The result i... | true |
7a6c27963f8e1adcba4b636cd29fdf598acdde0b | YeasirArafatRatul/Python | /reverse_string_stack.py | 492 | 4.125 | 4 | def reverse_stack(string):
stack = [] #empty
#make the stack fulled by pushing the characters of the string
for char in string:
stack.append(char)
reverse = ''
while len(stack) > 0:
last = stack.pop()
#here the pop function take the last character first thats why
... | true |
817a383769b024049a81ad3e76be36231099462d | YeasirArafatRatul/Python | /reverse_string_functions.py | 340 | 4.625 | 5 | def reverse_string(string):
reverse = "" #empty
for character in string:
"""
when we concate two strings the right string
just join in the left string's end.
"""
reverse = character + reverse
return reverse
string = input("Enter a string:")
result = reverse_string(st... | true |
2c5b1e85b26ea93a1f6636758db8889b28b7798a | tnotstar/tnotbox | /Python/Learn/LPTHW/ex06_dr01.py | 822 | 4.5 | 4 | # assign 10 to types_of_people
types_of_people = 10
# make a string substituting the value of types_of_people
x = f"There are {types_of_people} types of people."
# assign some text to some variables
binary = "binary"
do_not = "don't"
# make a string substituting last variable's values
y = f"Those who know {binary} and... | true |
833d91dfe8f65ce41b7dfa9b4ae15632a03e6170 | undefinedmaniac/AlexProjects | /Basic Python Concepts/if statements and loops.py | 1,580 | 4.40625 | 4 | # If statements are used to make decisions based on a conditional statement
# for example, the value in a variable could be used
variable1 = True
variable2 = False
if variable1:
print("True")
# else if statements can be added to check for additional conditions
if variable1:
print("Variable 1 is True")
elif ... | true |
971247c94cba717a85b4d900b0f93ae2bb6338a1 | radek-coder/simple_calculator | /run_it.py | 636 | 4.21875 | 4 | from addition import addition
from multiplication import multiplication
from division import division
from subtraction import subtraction
num_1 = int(input("Please insert your first number: "))
num_2 = int(input("Please insert your second number: "))
operation = input("Please insert your operation ")
if operation == ... | true |
f88b699c69329d90c31d9b9d18ca19bb7f671090 | Arl-cloud/Python-basics | /basics5.py | 2,327 | 4.28125 | 4 | #For loops: How and Why
monday_temperatures = [9.1, 8.8, 7.6]
print(round(monday_temperatures[0])) #print rounded number with index 0
#in 1st iteration, variable temp = 9.1, in the 2nd iteration 8.8
for temp in monday_temperatures:
print(round(temp)) #executed command for all items in an array
print("Done")
... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.