blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
3dd38e34a1fb2096193016dda9278e11b92cf478 | Bhasheyam/ALgorithms-PythonSolved | /Treesymentry.py | 574 | 4.28125 | 4 | '''Given a binary tree t, determine whether
it is symmetric around its center,
i.e. each side mirrors the other.'''
#
# Definition for binary tree:
# class Tree(object):
# def __init__(self, x):
# self.value = x
# self.left = None
# self.right = None
def isTreeSymmetric(t):
return mirro(t,t)
def m... | true |
7cf6ded8d4a2b0d4e60d7eb5696ac67c55bf1bce | alejandroge/PyDocs | /Pandas.py | 1,771 | 4.1875 | 4 | """
author: Alejandro Guevara
"""
import pandas as pd
import numpy as np
df = pd.read_csv('salaries.csv') # Create a DataFrame from a CSV file
print(df)
print(df['Name']) # Accessing data using its column name
print(df[['Name', 'Salary']]) # Accessing more than one column, using a list
... | true |
9a54f2fed3a924964bb72975bd57696dd2499aa2 | VishwajeetSaxena/selenium_python | /datatypes/string_part2.py | 1,080 | 4.34375 | 4 | #Access specific character of string
string1 = "This is sample string"
string2 = string1[3]
print("full string:", string1,"with type: ", type(string1))
print("specific character of string: ", string2, "with type: ", type(string2))
#Get length of string
print("Length of string is: ", len(string1))
#Get lower case data... | true |
666fcf93353f032029e9b974eb4d60c791ee55c5 | hravnaas/python_lessons | /cointosses.py | 600 | 4.1875 | 4 | # You're going to create a program that simulates tossing a coin 5,000 times.
# Your program should display how many times the head/tail appears.
import random
def flipCoin():
if round(random.random()) == 1:
return "head"
return "tail"
msg = "Attempt #{}: Throwing a coin... It's a {}! ... Got {} head(s) so far a... | true |
e0ca55619920753a3e2d3fa359dbf81b29fd2cab | hravnaas/python_lessons | /multiply.py | 401 | 4.125 | 4 | # Create a function called 'multiply' that reads each value in the list (e.g. a = [2, 4, 10, 16])
# and returns a list where each value has been multiplied by 5.
# The function should multiply each value in the list by the second argument.
def multiply(arr, multiplier):
for i in range(0, len(arr)):
arr[i] *= multip... | true |
bfa5e2c029fdb2f0789ad05f1983b6c5932a6fe5 | julianevan/Sandbox | /temperature.py | 1,220 | 4.375 | 4 |
"""
CP1404/CP5632 - Practical
Pseudocode for temperature conversion
"""
def calculate_celsius():
celsius = float(input("Celsius: ")) # float so as to allow decimal input
fahrenheit = celsius * 9.0 / 5 + 32 # formula for celsius to fahrenheit conversion
print("Result: {:.2f} F".format(fahrenheit)) # ... | true |
7df715ae08107b1efdb6633a0010c466ccacaf73 | niloo9876/marow | /example/example_functions.py | 1,119 | 4.4375 | 4 |
def mapper(chunk):
"""
The mapper function: process the raw text and returns the pairs name-value.
Args:
- chunk(str): the raw text from data file
Return(list of tuples): a list of 2D tuples with the pairs name-value.
"""
Pairs = []
for line in chunk.split('\n'):
data = line.s... | true |
ead64a142884de56aae8173d60b2a157c8870e37 | dettore/learn-python-exercises | /_beginners python 3 source files/strings.py | 520 | 4.40625 | 4 | name = "stefan mischook"
result = name.endswith('ook')
print(result)
# This is just a quick way (using the . operator,)
# to apply a method to an object. That's why you can't do this:
# name.upper()
# print(name)
# ... It will NOT be uppercase.
#
nameCap = name.upper()
print("Did I capitalize: " + nameCap)... | true |
957b84ecf88087f8528e9400b93aac5cc614e4ca | tmoertel/practice | /programming_praxis/dutch_national_flag.py | 1,989 | 4.125 | 4 | #!/usr/bin/python
#
# Tom Moertel <tom@moertel.com>
# 2013-03-05
"""Solve Dijkstra's "Dutch National Flag" problem.
http://programmingpraxis.com/2013/03/05/dutch-national-flag/
"""
# Our stategy is to partition A into red, mid, and blue segments,
# where the red segment A[:red] contains exclusively 'r' values, and... | true |
3dcec98ad917bb35c6344402d7921ca1878e5bb0 | gmckerrell/python-examples | /puzzles/collatz_template.py | 1,480 | 4.40625 | 4 | """
A Collatz sequence in mathematics can be defined as follows.
Starting with any positive integer:
if n is even, the next number in the sequence is n / 2
if n is odd, the next number in the sequence is 3n + 1
It is conjectured that every such sequence eventually reaches the number 1.
Test this conjecture.
Bonus... | true |
7d7f99ca0270914fb450d096e51e65abd688bdb8 | WLBailey0/Think-Python-2e | /ex9/ex9.9.py | 1,125 | 4.15625 | 4 | #!/usr/bin/env python3
"""
Exercise 9.9.
Here’s another Car Talk Puzzler you can solve with a search
(http://www.cartalk.com/content/puzzlers):
“Recently I had a visit with my mom and we realized that the two digits that make
up my age when reversed resulted in her age. For example, if she’s 73, I’m 37. We
wondere... | true |
e21eb2049f4282ea2d6500b241c6ad3a182961b9 | phaneendra-bangari/python-scripts | /Python Learning Scripts/PythonLoops/string_index.py | 417 | 4.53125 | 5 | #This script takes a string as input and locates its index values using loops.
INPUT_STRING=input("Enter a string to point their index values: ")
TEMP=0
for INDEX_VALUE in INPUT_STRING:
print(f"{INDEX_VALUE}->{TEMP}")
TEMP=TEMP+1
'''
INPUT_STRING=list(input("Enter a string to point their index values: "))
for... | true |
638b0ebd25b6004693ade97c067de0a63dfbe675 | ramr24/IntroToProg-Python | /num.py | 474 | 4.28125 | 4 | #Assignment_02
'''
Create a new program that asks the user to input 2 numbers
then prints out the sum, difference, product, and quotient.
'''
#Input 2 numbers
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
#Functions
add = num1 + num2
sub = num1 - num2
m... | true |
054179746facd0e8a44f1e5482431db85e8ff073 | premrajah/python3_101 | /03_timedelta.py | 1,386 | 4.28125 | 4 | #
# Comments go here
#
from datetime import date
from datetime import time
from datetime import datetime
from datetime import timedelta
def main():
# construct a basic timedelta and print it
print(timedelta(days=365, hours=5, minutes=1))
# print todays date
now = datetime.now()
print("Today is: "... | true |
cddbec89a0763c63b940d3769eee5995a436667d | GeorgePapageorgakis/Hackerrank | /Python/Numpy/Min Max.py | 1,456 | 4.25 | 4 | '''
min
The tool min returns the minimum value along a given axis.
import numpy
my_array = numpy.array([[2, 5],
[3, 7],
[1, 3],
[4, 0]])
print numpy.min(my_array, axis = 0) #Output : [1 0]
print numpy.min(my_array, axis = 1) #Output : [2 3 1 0]
print numpy.min(my_array, axi... | true |
5903846a864054d376f8eccb53f8439914e646ac | GeorgePapageorgakis/Hackerrank | /Python/Numpy/Concatenate.py | 1,060 | 4.3125 | 4 | '''
Concatenate
Two or more arrays can be concatenated together using the concatenate function with a tuple of the arrays to be joined:
import numpy
array_1 = numpy.array([1,2,3])
array_2 = numpy.array([4,5,6])
array_3 = numpy.array([7,8,9])
print numpy.concatenate((array_1, array_2, array_3))
#Output
[1 2 3 4... | true |
99922215e95feaeffa02710f863102a1b53399a0 | Northie17/Hugo-Python-Prep | /Meal tip program.py | 377 | 4.15625 | 4 | Name = input ("Please enter your name:")
Meal = float (input ("Please enter cost of meal:" ))
PercentTip = float (input ("Please enter percentage of tip :" ))
Tip = Meal/PercentTip
TotalCost = Meal + Tip
print ("The total cost for your meal is £{0:.2f} as the tip is £{1:.2f}".format(TotalCost,Tip))
print ("Thank you ... | true |
75b93f827f4e32a3a35268ad0c864b9109967c87 | ryanlei309/String-Practice-Game | /similarity.py | 2,342 | 4.3125 | 4 | """
File: similarity.py
Name: Ryan Lei
----------------------------
This program compares short dna sequence, s2,
with sub sequences of a long dna sequence, s1
The way of approaching this task is the same as
what people are doing in the bio industry.
"""
def main():
"""
After the user input a DNA sequence and... | true |
8c5a3b93bf20e527875e3404d5f294512b812b3a | oscarTinkerer37/My-tinkering | /listOfSquaresPalindromes.py | 1,301 | 4.125 | 4 | #list of squared numbers for finding palindromes
#Created on windows pc
import time, pprint
#A list of numbers with lengths of two or more digits (10-899 default) along with their squared values will be printed out.
#The program will alert the user when a non-palindromic base produces a palindromic square.
... | true |
4b65e823d7a08ee18ce55f9506f8713e4cc32b85 | nangia-vaibhavv/Python-Learning | /CHAPTER 6/03_quiz.py | 225 | 4.28125 | 4 | # write a program to print yes if age entered by userr is greater than or equal to 18
# as it is in string hence typecast it properly
age=int(input("enter your age: "))
if(age>=18):
print("yes")
else:
print("no")
| true |
a5ef3b05d17178110989c01946070b79b44a461a | VitaliyDuma/Python | /Task3.6.py | 329 | 4.21875 | 4 | place=int(input("Enter the number of your seat on the train: "))
if (place<=0) or (place>53):
print("Incorect date")
else:
if place%2==0:
print("place on top")
else:
print("place bottom")
if place>35:
print("place in side")
else:
print("place in conpartme... | true |
1de0b04856cf322ee10b1ed8f67e7375224a0895 | cugis2019dc/cugis2019dc-s-navya | /day3.py | 2,456 | 4.40625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jul 31 10:33:39 2019
@author: STEM
"""
# example 1; listing numbers of chocolate
Darkchocolate = 5
Milk = 6
White = 8
print(White)
#example 2: creating variables for the number of chcolates only
def cadburyBox(cadbury1,cadbury2,cadbury3):
print ("There ... | true |
990cc755fc4673d100f3e96e6db5bf57c30d2b2b | mick-io/codesignal | /arcade/python/7_simple_sort.py | 1,642 | 4.21875 | 4 | """Implement the missing code, denoted by ellipses. You may not modify the
pre-existing code.
To understand how efficient the built-in Python sorting function is, you
decided to implement your own simple sorting algorithm and compare its speed
to the speed of the Python sorting. Write a function that, given an array o... | true |
10239da9ba6ffe499af26b4e47ef0215644b72de | balbinfurio/higher_level_programming | /0x04-python-more_data_structures/7-update_dictionary.py | 311 | 4.125 | 4 | #!/usr/bin/python3
def update_dictionary(a_dictionary, key, value):
x = {key: value}
a_dictionary.update(x)
return (a_dictionary)
def print_sorted_dictionary(new_dict):
# imprimir dicts por elemento de forma "sort"
for i in sorted(new_dict):
print("{}: {}".format(i, new_dict[i]))
| true |
2f6723e0d24aeaae6045f24d9a9f9af64d0bae91 | 3rrorBaralasch/SmallStuff | /Calculator.py | 1,385 | 4.1875 | 4 | def helpFunc():
print ("""
Welcome to my Program, here you can do Text Mathematical Calculations.
......................................................................
(!) Help
-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_
Functions:
For Division--------------[D]... | true |
8d89099b3a3b058636737bb05bb5a5c5cb5617e6 | gateway17/holbertonschool-higher_level_programming | /0x08-python-more_classes/1-rectangle.py | 2,422 | 4.15625 | 4 | #!/usr/bin/python3
"""
Write a class Rectangle that defines a rectangle by: (based on 0-rectangle.py)
Private instance attribute: width:
property def width(self): to retrieve it
property setter def width(self, value): to set it:
width must be an integer, otherwise raise a TypeError exc... | true |
d05f9b602f79c417b8a2a5213b3fe96ab59b8912 | gateway17/holbertonschool-higher_level_programming | /0x03-python-data_structures/3-print_reversed_list_integer.py | 568 | 4.5625 | 5 | #!/usr/bin/python3
# Write a function that prints all integers of a list, in reverse order.
#
# Prototype: def print_reversed_list_integer(my_list=[]):
# Format: one integer per line. See example
# You are not allowed to import any module
# You can assume that the list only contains integers
# You are ... | true |
aabe501115b14636054ce1ae6693886aa33d8a3a | gateway17/holbertonschool-higher_level_programming | /0x05-python-exceptions/2-safe_print_list_integers.py | 1,154 | 4.25 | 4 | #!/usr/bin/python3
"""
Write a function that prints the first x elements of a list and only integers.
Prototype: def safe_print_list_integers(my_list=[], x=0):
my_list can contain any type (integer, string, etc.)
All integers have to be printed on the same line followed by a new line
- other type of v... | true |
074e6a6ff06ab012bd1069e8d9c88314ac97dd3b | gateway17/holbertonschool-higher_level_programming | /0x03-python-data_structures/6-print_matrix_integer.py | 745 | 4.21875 | 4 | #!/usr/bin/python3
# Write a function that prints a matrix of integers.
# Prototype: def print_matrix_integer(matrix=[[]]):
# Format: see example
# You are not allowed to import any module
# You can assume that the list only contains integers
# You are not allowed to cast integers into strings
# You h... | true |
c8795dd672e363f5aae4fe1df78326b7101edc48 | gateway17/holbertonschool-higher_level_programming | /0x0B-python-input_output/0-read_file.py | 540 | 4.25 | 4 | #!/usr/bin/python3
"""
Write a function that appends a string at the end of
a text file (UTF8) and returns the number of characters added:
Prototype: def append_write(filename="", text=""):
If the file doesn’t exist, it should be created
You must use the with statement
You don’t need to manage file per... | true |
6be7ca21623214baf5c5c28b8fd6d47a0d80d0db | mgarmos/LearningPython | /RegularExpression/Pr01.py | 1,612 | 4.34375 | 4 | # Search for lines that contain 'From'
import re
hand = open('mbox-short.txt')
for line in hand:
line = line.rstrip()
if re.search('From:', line): #equivalent line.find()
print(line)
hand.close()
print('----------')
# Search for lines that start with 'From'
hand = open('mbox-short.txt')
for line in hand:
... | true |
ca561a8b613e7e24a1733c3aee62e3587b25d909 | aryan-upa/learn-python39 | /lab-python/panagram_string.py | 675 | 4.125 | 4 | """
Determine if a sentence is a pangram. A pangram is a sentence using every letter of the
alphabet at least once. The best known English pangram is:
“The quick brown fox jumps over the lazy dog”.
The alphabet used consists of ASCII letters A to Z, inclusive, and is case insensitive. Input will not
contain non-ASCII... | true |
e28acb120d1e1a3b73933105aba5a26b931f9a4c | maybe-william/holbertonschool-higher_level_programming | /0x08-python-more_classes/7-rectangle.py | 2,188 | 4.21875 | 4 | #!/usr/bin/python3
""" This module defines a rectangle. """
class Rectangle:
""" A rectangle """
number_of_instances = 0
""" the number of rectangle instances in existence """
print_symbol = '#'
""" the print symbol"""
def __verify_int(self, value, tp):
""" Verify an int """
... | true |
884695b6c9a49aa335cc0df94c32e3b9cbd01268 | alenasf/advanced_topics_in_python | /json_example.py | 2,398 | 4.1875 | 4 | import json
"""Example_1: Using JSON with Python
json.loads(convert JSON string into Python dict)
json.load(convert JSON file into Python dict)
json.dumps(convert Python dict into JSON string)
json.dump(convert Python dict into JSON file)
"""
# open the file example.json. Convert JSON file to dict
f = open("exampl... | true |
06b0d5d6985c1e54a0834d42bf7101a3faefa6bf | projectinnovatenewark/csx | /Students/Semester2/lessons/students/3_classes_and_beyond/19_try_except_finally/19_try_except_finally.py | 2,389 | 4.4375 | 4 | """
try/except/finally with error handling
"""
# here, we will try to open a test.txt file. Since there is no test.txt file,
# we will raise an exception using "except". Since our try creates an error then the
# exception will be raised, and the finally code block executes thereafter.
try:
f = open("test.txt", 'r... | true |
487d16afcb27a53d2ec35917185d927da14de8f1 | projectinnovatenewark/csx | /Students/Semester2/lessons/archive/20_advanced_functions/20_advanced_functions_and_args.py | 2,318 | 4.96875 | 5 | """
Learning more advanced functions and navigating loops through dictionaries
"""
# *args being set in a function's parameters allows additional arguments to be passed. They will
# turn into a tuple named after what you put following the asterisk. **kwargs being set in a function's
# parameters allows additional arg... | true |
af342b751513b419b0e7c8e875eb956996189c8a | projectinnovatenewark/csx | /Students/Semester1/lessons/2_python/13_classes/13_classestodo.py | 1,380 | 4.5 | 4 | """
Creating classes for your classmates
"""
# TODO: Section 1
# Define a class of "Dog". Ensure that all of the class instantiations of "Dog" have a
# property of "animal_type" set to "mammal". This dog should have some attributes set
# in it's init function including name, breed, and age.
# TODO:
# Instantiate an ... | true |
1dfad88b9ee12061af4d188b603464df6f1afd4b | danieldizzy/CodeCademy | /NumberGuess_new.py | 1,595 | 4.625 | 5 | """ We'll build a program that rolls a pair of dice and asks the user to guess a number. Based on the user's guess, the program should determine a winner. If the user's guess is greater than the total value of the dice roll, they win! Otherwise, the computer wins.
The program should do the following:
Randomly ro... | true |
41c7d53e3408dc93aeb4917bf542efa2e1b3a1a1 | danieldizzy/CodeCademy | /RockScissorsPaper.py | 2,298 | 4.5 | 4 | """In this project, we'll build Rock-Paper-Scissors!
The program should do the following:
Prompt the user to select either Rock, Paper, or Scissors
Instruct the computer to randomly select either Rock, Paper, or Scissors
Compare the user's choice and the computer's choice
Determine a winner (the user or the co... | true |
7856ca6e19ec8120307027f641d2bbd5c476406e | jtpunt/python | /palindrome.py | 1,404 | 4.21875 | 4 | # Author: Jonathan Perry
# Date: 9/6/2018
import re
import math
# Iterates through n/2 characters of the string str, where the first half of the characters are checked
# against the 2nd half of characters (where the 2nd half is in reversed order) match the first half of characters.
# For example, assume we split the st... | true |
12af2f2479387d120c84c3890549e28fcd968c4d | lemire/talks | /2022/evil/week2/parabolic.py | 315 | 4.1875 | 4 | import math
v = float(input("What was the velocity of the throw? "))
angle = float(input("What was the angle of the throw? "))
g = 9.81
h = float(input("What was your intial height? "))
maxHeight = h + v*v * (math.sin(math.radians(angle)) * math.sin(math.radians(angle))) / (2 * g)
print("maxheight = ", maxHeight) | true |
b61e74e9dca19dd771ee679ad84a4da175dc8137 | abhinav-m/python-playground | /tutorials/basics/data-structures/lists/lists_methods.py | 988 | 4.21875 | 4 | # index method which returns index of given value
numbers = [1, 2, 3, 2, 5, 6]
print(numbers.index(2))
# prints the first 2 found (index 1)
# optional arguments -> start, stop
# starts looking for given argument from index 1.
print(numbers.index(2, 1))
# prints 1
# prints 3
print(numbers.index(2, 2))
names = ["Abh... | true |
8fa4ea627354a68fb3c9c18c9d9c0df9fd39a266 | abhinav-m/python-playground | /tutorials/basics/datatypes.py | 1,037 | 4.1875 | 4 | # Some common datatypes.
# bool -> true/false
test = True # Assigning true to test, notice capital T
test_2 = False # Uppercase F for false.
some_string = "A string"
test_array = [1, 2, 3, 4] # List datatypes.
print(type(test_array))
print(type(some_string))
print(test)
# Python has dynamic data types.
# Varia... | true |
577370e276189e577e049eb70ad55bb68d457d0b | abhinav-m/python-playground | /tutorials/basics/math_example.py | 319 | 4.71875 | 5 | # Exponentiation operator -> **
print(2**3) # should print 8
# Can also be used for roots.
print(81**0.5) # Note result is a float.
print(27**0.33) # Cube root example.
# Regular division returns floats.
print(3/2) # This will result a float.
# Integer division operator -> //
print(3//2) # Returns an integer.
| true |
d88fbf65dc524e154212937ed5a19d97cb79a17e | abhinav-m/python-playground | /tutorials/basics/data-structures/dictionaries/dictionaries.py | 1,068 | 4.25 | 4 | # Dictionaries are a data structure consisting of key -value pairs (same as objects / maps in javascript or java)
cat = {"name": "blue", "age": 3.5, "isCute": True}
print(cat)
# Another way to create a dictionary
dictionary_2 = dict(name="Abhinav", age="25", works="b4s")
print(dictionary_2)
age_str = "age"
# Acce... | true |
abb82c878df8cf3c6e393845a1cff6b17f0ca926 | zssasa/Bioinformatics | /Bioinformatics6/week1/Trie.py | 1,478 | 4.15625 | 4 | # -*- coding: utf-8 -*-
__author__ = 'zhangsheng'
from pprint import pprint
_end = '$'
def make_trie(words):
"""
CODE CHALLENGE: Solve the Trie Construction Problem.
Input: A collection of strings Patterns.
Output: The adjacency list corresponding to Trie(Patterns), in the following format. If
Trie(Patterns) has... | true |
8cf209473b573803489634ce2f18be49c51e5094 | baldure/first_git_project | /max_int.py | 320 | 4.25 | 4 |
num_int = int(input("Input a number: ")) # Do not change this line
num_2_int=num_int
max_int=0
while num_2_int > 0:
if num_2_int > max_int:
max_int = num_2_int
num_2_int = int(input("Input a number: "))
# Fill in the missing code
print("The maximum is", max_int) # Do not change this line
| true |
bf1d93a5c0be8b746256fe975b7c8048a000982f | holland11/boat_datasatore_csc462_project | /trimmed_to_duplicated.py | 1,524 | 4.21875 | 4 | '''
Program that takes a csv as input and returns a csv as output.
The output csv will have duplicated rows from the input csv, but at least
one column will be slightly modified for each duplicate so they aren't identical.
'''
import csv
import random
num_duplicates = 200 # 200 = 2,500 rows -> 500,000 rows
... | true |
a13ae691072772ea8c5f018129c4014116f50192 | sdp43/BIOSC1640Project1 | /pseudocode/calculateSphere.py | 1,882 | 4.46875 | 4 | def ritters_bounding_sphere(pointlist):
"""This definition uses Ritter’s algorithm to calculate a non-minimal bounding sphere for a set of points.
The sphere calculated is likely to be 5-20% larger than the optimal sphere.
:param pointlist: list of points for which sphere is to be calculated
:type pointlist: list ... | true |
537396c441a80fa859e210be3b7fc6c8cf56e6a8 | sunnyvineethreddy/Python | /ICPS/ICP2/PythonICP2/gameboard1.py | 345 | 4.125 | 4 | heightinp= int(input("Enter the height of the board: "))
widthinp= int(input("Enter the width of the board: "))
def board_draw(heightinp,widthinp):
for temp in range(heightinp):
print(" --- " * widthinp)
print("| " * widthinp, end="")
print("|")
print(" --- " * widthinp)
board_draw... | true |
772f2b75781eaaf260d2f7d706492d16cc96cf4b | dinhtq/coding_practice | /arrays/reverse_polish.py | 1,779 | 4.40625 | 4 | """
Given an arithmetic expression in Reverse Polish Notation, write a program to evaluate it.
The expression is given as a list of numbers and operands. For example: [5, 3, '+'] should return 5 + 3 = 8.
For example, [15, 7, 1, 1, '+', '-', '/', 3, '*', 2, 1, 1, '+', '+', '-'] should return 5,
since it is equivalent... | true |
37607a20cdbfd82ec43867a00aa8f04a10b622ed | SiddhantAshtekar/python-algorithem-for-begginers | /chap_5/into_list.py | 423 | 4.53125 | 5 | # Data stucture
# List ---->this chapter
# ordered collection of items
# you can store anything in lists int , float ,string
numbers=[1,2,3,4]
print(numbers)
print(numbers[1])
words=['word1','word2','word3']
print(words)
print(words[:2])
mixed =[1,2,3,4,"five","six",2.3,None]
print(mixed[1:3])
mi... | true |
ee028f9656663d29867e76989785dd802e98ec2a | jefflike/leetcode | /009. Palindrome Number/Palindrome Number.py | 2,992 | 4.3125 | 4 | '''
__title__ = 'Palindrome Number.py'
__author__ = 'Jeffd'
__time__ = '4/23/18 10:57 PM'
'''
'''
tips:
Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
Example 1:
Input: 121
Output: true
Example 2:
Input: -121
Output: false
Explanation: Fro... | true |
212a7167d1d5bfb7205f02c0a9ebba4e41c09eb8 | chapman-cpsc-230/hw4-agust105 | /count_pairs.py | 478 | 4.1875 | 4 | """
File: count_pairs.py
Copyright (c) 2016 Francis Agustin
License: MIT
Wrote a program that returns the number of
occurrences of a pair of bases in a DNA strand.
"""
['A', 'T', 'G', 'C']
def count_v2(dna,pair):
i = 0
for AT in dna:
if AT == pair:
i += 1
return dna.count(pair)
dna... | true |
2e253d9af0bcd8f37ef35ada20ed7cde761c9ea6 | kmalakhova/grokking_algorithms | /01_introduction_to_algorithms/01_binary_search.py | 668 | 4.1875 | 4 | def binary_search(sorted_list,value):
'''
Returns the amount of steps needed to guess the given value.
If value exists in sorted_list, return its sequence number.
if not, return None.
Assume the list is sorted from smallest to largest.
'''
low = 0
high = len(sorted_list) - 1
while ... | true |
bfb03dee83fa21c107bcd73db1890eb91fd7850b | yosoydead/exercises | /encrypt this/file.py | 1,725 | 4.375 | 4 |
#string = "Hello world this is a sample text"
#string = "A wise old owl lived in an oak"
string = "The more he saw the less he spoke"
def x(string):
result = ""
#if the string is empty, return an empty string
if string == "":
return ""
else:
#split the string into an array containing e... | true |
c54a93bc172879dfeaa10cf4abd8261d1bf3c796 | yosoydead/exercises | /playing with digits/file.py | 1,187 | 4.125 | 4 | #the main function
def bla(number, start):
#this is the inner function
#it made it easier for me to execute the calculations
#this way i don't modify either parameter given
def inner():
#for ease of use, i converted the number param into a string to iterate
#over it one character at a t... | true |
f44605e7763eb0fd7c96a34ce345bb6f029d3cf8 | ComteAgustin/learning-py | /conditionals.py | 672 | 4.625 | 5 | # Conditionals
# Comparisons operators
3 > 2 # Greater-than
3 < 2 # less-than
3 == 3 # same-than
3 != 2 # not same-than
3 <= 2 # less and same-than
3 >= 5 # greater and same-than
# Logical operators
3>2 and 2>2 # if both conditions are true, return true
3>2 or 2>2 # need one of the conditions true, for return tru... | true |
4a8a868b6f5ec259da9feeec52bb13c7a7c1403d | mcgeorgiev/Python-and-Pi_Workshop | /examples/1_hello.py | 653 | 4.28125 | 4 | # this is a comment. use to annotate your programmes
# programmes are generally read top to bottom
# this is a print function. it will display text on screen
print('Hello, world.')
print('Today is Tuesday the 16th of February')
# this is a variable. it is a placeholder for some information
animal = 'cat'
# you can ... | true |
5080a821ba140287f90c8fc55600ee754a50edf7 | Tanuka-Mondal/Python | /diff and double.py | 423 | 4.25 | 4 | #Write a Python program to get the difference between a given number and 17, if the number is greater than 17 return double the absolute difference.
def difference(n):
if n <= 17:
return 17 - n
else:
return (n - 17) * 2
num = int(input("Enter a number: "))
dif = difference(num)
print("The a... | true |
8ae569baaeccecb572fc396056034e156bb0de69 | afcarl/machine-learning-python-examples | /supervised-learning/02-find-best-k-by-looping.py | 1,643 | 4.3125 | 4 | # This example uses the digits dataset to illustrate how to find the best k
# value using for loop
# Outcome: A plot of k vs prediction accuracy
# Import necessary modules
from sklearn import datasets
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split
import numpy a... | true |
3b5bdc032b47fca6316662bb2078a7e417bde3d8 | ambercyang/mcit582hw1 | /caesar.py | 983 | 4.25 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[6]:
def encrypt(key,plaintext):
ciphertext=""
#YOUR CODE HERE
# transverse the plain text
for i in range(len(plaintext)):
char = plaintext[i]
# Encrypt uppercase characters in plain text
ciphertext += chr((ord(char) + key-65) % 26 + 65)
... | true |
c0dc26bec1486217a4578a1fa4b6ca9c43d142ae | JarettSisk/python-data-structures-practice | /17_mode/mode.py | 617 | 4.125 | 4 | def mode(nums):
"""Return most-common number in list.
For this function, there will always be a single-most-common value;
you do not need to worry about handling cases where more than one item
occurs the same number of times.
>>> mode([1, 2, 1])
1
>>> mode([2, 2, 3, 3, 2])
... | true |
d137c58f90c26ee84ea3182b18c73168c91e6c0c | ANDRESOTELO/holbertonschool-higher_level_programming | /0x0B-python-input_output/1-write_file.py | 335 | 4.40625 | 4 | #!/usr/bin/python3
"""Function that writes a string"""
def write_file(filename="", text=""):
"""
Function that writes a string
to a text file (UTF8) and returns
the number of characters written
"""
with open(filename, 'w') as input_text:
num_chars = input_text.write(text)
retu... | true |
03c4b4678b29ec1002653eda86ed9ea742fcbf8d | Ishant-Dhall/Python-Programs | /Prime No.py | 441 | 4.28125 | 4 | #Prime or not
print 'THE FOLLOWING PROGRAM CHECKS WHETHER A GIVEN NO IS A PRIME NO OR NOT'
x=input('Input the number: ')
count=0
if x<0: print 'This is a negative number'
elif x==1: print '1 is neither a prime nor a composite number'
else:
for n in range (1,(x/2)+1):
if x%n==0: count=count+1
if... | true |
d48f2a992fbdc928e899be4caae85d3f42c6c623 | Ishant-Dhall/Python-Programs | /List-Find & Remove.py | 558 | 4.34375 | 4 | #Finding Element in a list
print "THE FOLLOWING PROGRAM SEARCHES FOR AN ELEMENT IN A LIST"
list=['January','February','March',
'April','May','June',
'July','August','September',
'October','November','December']
str=raw_input("Enter the element you want to find and remove: ")
for i in range (0,l... | true |
23b5ff82682b3650e7d69aa705cd0b78a232fca3 | sakuya13/Study | /python/lectures/week07&08/example3_nestedfor_whilesimple_prime.py | 635 | 4.25 | 4 | ## to calculate if a number is prime or not
"""
for num in range(1,20): #to iterate between 1 to 20
for i in range(2,num): #to iterate on the factors of the number
if num%i == 0: #to determine the first factor
print(num, 'is not prime')
break
else:
print (num, ... | true |
47de2a2c5bb1f754ff157892f28c21f0c654b9c5 | sakuya13/Study | /python/lectures/week05/lecture5_example_calc_sum_user(1).py | 628 | 4.34375 | 4 | #this program calculates the sum of the five numbers entered by the user
# these examples illustrate the range count and what they do- take a look
sum = 0.0
print('This program will calculate the sum of five numbers')
print('that you will enter')
'''
for counter in range(5):
number = int(input('enter a number:'))
... | true |
021175d50dca2bcb124c293a2e1b9b000eb6ce20 | sakuya13/Study | /python/lectures/week07&08/example_remove_list.py | 288 | 4.375 | 4 | # example to illustrate the remove().
food = ['pizza', 'burger', 'chips']
print(food)
item = input('which item would you like to remove:')
if item not in food:
print('the item is not in the list')
else:
food.remove(item)
print('here is the new list:')
print(food)
| true |
0291bdb02a81dcc5d6a5243a7f89231ae9a2383f | sakuya13/Study | /python/lectures/week03/example2_lect3_input_instead_print.py | 311 | 4.375 | 4 | """
This example code illustrates using the input statement to gather values from the user
Note: what happens to this piece of code? Is there a problem!
"""
width = int(input ("please enter the width = "))
height = int(input ("please enter the height = "))
area = width * height
print ("the area is = ", area)
| true |
1a9bf864aecf7253dacdd59a24f3e65814365ac8 | sakuya13/Study | /python/lectures/week06/example_format-style_empty.py | 248 | 4.15625 | 4 | count = 10
total = 100
print("The number contains {} digits".format(count))
print("The digits sum to {}".format(total))
#example - check the string
success = 'Congratulations, you have scored "{}" out of "{}"'
print(success.format(count, total))
| true |
1ff84c91dafdf2fcff288ecd4fdb95fe594a45ad | RayWLMo/Eng_89_Python_OOP | /Python_Functions.py | 1,438 | 4.65625 | 5 | # Let's create a function
# Syntax -> def is used to declare followed by name of the function():
# First iteration
def function():
print("This is a function")
# pass # pass is the keyword that allows the interpreter to skip this without any errors
function() # To call the function
# If the function is not c... | true |
aa77b37721682d2c39921670950a1dfad4ac7f03 | Youngshark3/100-DaysOfCode-Python | /Day 5/day-5-2-highest-score.py | 1,612 | 4.53125 | 5 | # Highest Score
# Instructions
# You are going to write a program that calculates the highest score from a List of scores.
# e.g. student_scores = [78, 65, 89, 86, 55, 91, 64, 89]
# **Important**
# You are not allowed to use the max or min functions.
# The output words must match this example:`The highest score in ... | true |
8310538cc5cc92c48735057b2129198be020f175 | Youngshark3/100-DaysOfCode-Python | /Day 4/day-4-2-random-person-pays-bill.py | 1,512 | 4.46875 | 4 | # Who's Paying
# Instructions
# You are going to write a program which will select a random name from a list of names. The person selected will have to pay for everybody's food bill.
# **Important**: You are not allowed to use the `choice()` function.
# **Line 20** splits the string `names_string` into individual name... | true |
ed5649b9a496cec3db37971b0ad220a26b13bf10 | Youngshark3/100-DaysOfCode-Python | /Day 4/day-4-3-treasure-map.py | 2,348 | 4.96875 | 5 | # Treasure Map
# Instructions
# You are going to write a program which will mark a spot with an X.
# In the starting code, you will find a variable called `map`.
# This ```map``` contains a nested list.
# When ```map``` is printed this is what the nested list looks like:
# ['⬜️', '⬜️', '⬜️'],['⬜️', '⬜️', '⬜️'],['⬜️',... | true |
b38b57291b95635f0136a09ee606f0d8a02e6984 | Youngshark3/100-DaysOfCode-Python | /Day 5/day-5-4-fizz-buzz.py | 1,472 | 4.53125 | 5 | # FizzBuzz
# Instructions
# You are going to write a program that automatically prints the solution to the FizzBuzz game.
# `Your program should print each number from 1 to 100 in turn.`
# `When the number is divisible by 3 then instead of printing the number it should print "Fizz".`
# `When the number is divisib... | true |
65c1684ecaa2a70b9148781e22ac7873c81b1b70 | Youngshark3/100-DaysOfCode-Python | /Day 8/day-8-1-area-calc.py | 1,549 | 4.53125 | 5 | # Area Calc
# Instructions
# You are painting a wall. The instructions on the paint can says that **1 can of paint can cover 5 square meters** of wall.
# Given a random height and width of wall, calculate how many cans of paint you'll need to buy.
# number of cans = (wall height ✖️ wall width) ÷ coverage per can.
# e... | true |
4882708ae69e7e302fb695edf175782682905660 | archime/codewars | /valid-braces.py | 665 | 4.34375 | 4 | """
Title: Valid Braces
Write a function that takes a string of braces, and determines if the order of the braces is valid. It should return true if the string
is valid, and false if it's invalid. This Kata is similar to the Valid Parentheses Kata, but introduces new characters: brackets [], and
curly braces {}. Than... | true |
36596a865a2d6c7141b508aa8949c3780f03eb2e | UmairKhankhail/OOPs | /Class and Instance Variables.py | 1,200 | 4.3125 | 4 | #Instance Variables
#Class/Static Variables (Class varaibles are also called static varaibles.)
class Car():
#Class variables
body='Metal'
def __init__(self):
self.Type="BMW"
self.Mileage=2000
car1=Car()
car2=Car()
#Now If I call the variables for both the objects, this will give us... | true |
ae1ec1aff6d69ff18535545016c568228df288ab | rubentrevino95/python-exercises | /exercises/strings.py | 745 | 4.125 | 4 | a = 10
b = 3.14
c = "Hello World"
d = 'tinker'
print(a + a)
print(d[1:4])
# Data Types
print(type(a))
print(type(b))
print(type(c))
# length of string
print(len(c))
# index of string
print (c[1])
# slicing
print (c[:3])
# sub section slicing
print (c[3:6])
# beginning to end rev
print (c[::-1])
# beginning to... | true |
a80cd106d0a1e022396e6825ef297f89bfc45544 | kajalgada-gmr/leetcode-python | /leetcode_617_merge_two_binary_trees/leetcode_617_merge_two_binary_trees.py | 1,503 | 4.25 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def mergeTrees(self, root1: TreeNode, root2: TreeNode) -> TreeNode:
# If either or both tre... | true |
462a9af8672830e6de07133583e5ab5b0600f8a7 | lambda-projects-lafriedel/Sorting | /src/recursive_sorting/recursive_sorting.py | 2,146 | 4.21875 | 4 | # TO-DO: complete the helper function below to merge 2 sorted arrays
def merge( arrA, arrB ):
# These 2 lines are creating a new list that has the length of 'elements' and is being instantiated with 0s as placeholders
elements = len( arrA ) + len( arrB )
merged_arr = [0] * elements
# Need to keep track... | true |
98ee613ea7335b360e7fcadbff1f86eb0a147abb | Ch4insawPanda/CP1404_Practical | /prac_05/emails.py | 1,477 | 4.40625 | 4 | def main():
email_to_name = {}
user_email = input("Enter Email :")
while user_email != '':
user_email = get_user_name(email_to_name, user_email)
for name, email in email_to_name.items():
print('{} {}'.format(name, email))
def get_user_name(email_to_name, user_email):
"""Check if th... | true |
c750a3bb24c536152394f98ee6500ffa46008ae5 | jgramelb/Python-learning | /ex12_07.py | 1,690 | 4.28125 | 4 | #12.7
#Exercise 4 from book
#Instructions:
#Change the urllinks.py program to extract and count paragraph (p) tags from the
#retrieved HTML document and display the count of the paragraphs as the
#output of your program. Do not display the paragraph text, only count them.
#Test your program on sever... | true |
332fb5f30bcf3faae4d1de96ac0bde81a2bd883e | jgramelb/Python-learning | /ex02_04.py | 340 | 4.1875 | 4 | #Exercise 4: Assume that we execute the following assignment statements:
#width = 17
#height = 12.0
#For each of the following expressions, write the value of the expression and the type (of the value of the expression).
width = 17
height = 12.0
print(round(width//2))
print(round(width/2.0))
print(round(height/3))
... | true |
8f6ade43f1e8baf6a6091f1ad01d426f73cf6d90 | jgramelb/Python-learning | /ex08_05.py | 954 | 4.3125 | 4 | #ex8.5
# 8.5 Open the file mbox-short.txt and read it line by line.
# When you find a line that starts with 'From '
# like the following line:
# From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008
# You will parse the From line using split() and
# print out the second word in the line
#... | true |
aab14e0a5be87e456fdb4692241d5a0c427cf557 | caiknife/test-python-project | /src/ProjectEuler/p059.py | 2,203 | 4.34375 | 4 | #!/usr/bin/python
# coding: UTF-8
"""
@author: CaiKnife
XOR decryption
Problem 59
Each character on a computer is assigned a unique code and the preferred standard is ASCII (American Standard Code for Information Interchange). For example, uppercase A = 65, asterisk (*) = 42, and lowercase k = 107.
A modern encryptio... | true |
192cf81d9c683256b4f3d58a2701c99950159992 | srirachanaachyuthuni/Basic-Programs-Python | /reverse.py | 425 | 4.28125 | 4 | '''
Print the reverse of a number
'''
def reverse(x):
if (x < 0):
x = abs(x)
return(-1 * reverse_recursive(x,0))
else:
return(reverse_recursive(x,0))
def reverse_recursive(n,rev):
if n == 0:
return int(rev)
else:
i = n % 10
rev = rev * 10 + i
n = ... | true |
1d5fac9749533969f4aec92f8a5388c66f86ec18 | An022/simple_calculating | /03_quadratic_solver/quadratic_solver.py | 1,487 | 4.34375 | 4 | """
File: quadratic_solver.py
Name: An Lee
-----------------------
This program should implement a console program
that asks 3 inputs (a, b, and c)
from users to compute the roots of equation:
ax^2 + bx + c = 0
Output format should match what is shown in the sample
run in the Assignment 2 Handout.
"""
import math
imp... | true |
a034a5ba12a0fb5b6160dc92c5bc76d50e333472 | cmnetto/PSU_GEO0485 | /PennState_Data/Lesson2results/practice01.py | 418 | 4.34375 | 4 | #Lesson 2 Practice Exercise 01
#Find the spaces in a list of names-
#Then write code that will loop through all the items in the list, printing a message like the following:
#"There is a space in ________'s name at character ____."
beatles = ["John Lennon", "Paul McCartney", "Ringo Star", "George Harrison"]
for name ... | true |
b448790814b573ea3795e6fec3f81e9be5eea1d2 | Kumar72/PyCrashCourse | /Introduction/chapter_4.py | 2,335 | 4.40625 | 4 | # Working with Lists
# EX: 4.1
pizzas = ['Veggie Lovers', 'Buffalo Chicken', 'Meat Lovers', 'Mediterranean']
for pizza in pizzas:
print(pizza.title())
print('I can eat pizza for days!\n')
# the colon indicated the start of a for loop
# indent only when you are suppose to, as it is part of certain syntax ex. for lo... | true |
61122474777f34046f69b1a5873084740dc0ca31 | QuantumNovice/math-with-python | /monte_carlo_pi.py | 526 | 4.125 | 4 | import random
NUM_POINTS = 10000
# Generates random numbers between -1 and 1
def rand(): return random.uniform(-1,1)
# Generate a bunch of random points in the square which inscribes the unit circle.
points = [(rand(), rand()) for i in xrange(NUM_POINTS)]
# Find all points which are inside the circle - i.e. points ... | true |
bc25392f3df0f6fb26920374a477e6bfda204f14 | MileyWright/cs-module-project-recursive-sorting | /src/sorting/sorting.py | 1,638 | 4.1875 | 4 | # TO-DO: complete the helper function below to merge 2 sorted arrays
def merge(arrA, arrB):
elements = len(arrA) + len(arrB)
merged_arr = [0] * elements
# Your code here
a_counter = 0
b_counter = 0
for i in range(0, elements):
if a_counter == len(arrA) or b_counter == len(arrB): ... | true |
09cbf67dd7234e78e48f66dad97724c4d38ee459 | JANMAY007/python_practice | /Python language practice/python practice questions/smallest_divisor.py | 240 | 4.15625 | 4 | number=int(input('Enter the number whose smallest divisor you want:'))
divisor=[]
for i in range(1,number+1):
if(number%i==0):
divisor.append(i)
divisor.sort()
print("The smallest divisor of %d is %d."%(number,divisor[0])) | true |
977539bd5a71a67ea02b097f832066891d9ae0be | asingh21/python | /data_structures/linked_list/prac/linkedlist_insert_end.py | 595 | 4.15625 | 4 | from linked_list import Node
from linked_list import LinkedList
def insert_at_end(head, data):
temp = head
while temp.next:
temp = temp.next
node_to_insert = Node(data)
temp.next = node_to_insert
if __name__ == '__main__':
data_to_insert = 5
linked_list = LinkedList()
llist = [1,... | true |
5e70f534ccc4455d4142a9d39c4ad12801541f05 | danzhou108/insertionsort | /InsertionSort.py | 652 | 4.1875 | 4 | def InsertionSort(input): #passes a 1-D array for insertion sort
for ind in range(1,len(input)):
val = input[ind] #get value of current key
prevInd = ind-1 #get position of previous index
while prevInd>=0 and input[prevInd]>val: #check for conditions: 1) index is in the first pos or high... | true |
0f23c6652ceacec218afacdbf1766f43414c5833 | derick-droid/pirple_python | /dict_set.py | 654 | 4.3125 | 4 | # black shoes shelves with sizes customers choose the size they wish to buy
# if chosen the stock decreases and no one is allowed to choose zero and negative numbers
black_shoes = {45: 2, 32: 4, 44: 4, 23: 5, 40: 2}
while True:
choice = int(input("enter your size: "))
if choice <= 0:
print("invalid sho... | true |
dfeb1bde407ce1eb034e0382bb009508884c3d6f | jwflory/python-howto-read-yaml | /read_yaml.py | 1,185 | 4.4375 | 4 | #!/usr/bin/env python3
"""
A brief introduction to Python data objects. Refer to official Python docs or
other online resources for more detailed explanations.
list:
- one
- two
- three
list[0] -> return str
list[1] -> return str
dict:
- "one": "first number"
- "two": "second number"
- "three": "thir... | true |
1950e56dfaaa1eb686c71a41bf13f8f6a0bc8d9e | JohnBomber/mon_python | /Practice_Python/Birthday dictionaries.py | 608 | 4.59375 | 5 | birthday = {"Ben":"02/07/1980",
"Franck":"19/08/1985",
"Yann":"16/04/1988"}
print("Welcome to the birthday dictionary. We know the birthdays of:")
for name in birthday:
print(name)
name = input("Who's birthday do you want to look up?\n")
if name in birthday:
print("{}'s birt... | true |
64a9c577acb0624d14b1a93f4d077f731e1c6be8 | ama0322/Algorithms-in-Python | /leetcode-in-python/medium_difficulty/ZigZag Conversion.py | 2,690 | 4.1875 | 4 | def Solution(s, numRows):
"""
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to
display this pattern in a fixed font for better legibility)
P A H N
A P L S I I G
Y I R
And then read line by line: "PAHNAPLSIIGYI... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.