blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
81d9f5da43cf0202976016bc9c2dd298eddf046f | Corinyi/Engineering_Computer_Programming | /assignments+exam/mideterm/2019314417.py | 2,293 | 3.9375 | 4 | print("""
=========================
====2019314417 이윤서====
=========================
""")
user=[3,2,1,4]
com=[2,4,6,8]
while True:
print("\nUser cards: " ,user)
print("Com cards: ",com)
print("1. discard a card")
print("2. receive a card")
print("3. confirm win/loss(upgraded)")
... |
2199b5715c73aacddd7dbd97e5253e3b85e45aac | 258356/DailyPractice | /python_programming_submission/ifelse_3.py | 128 | 3.875 | 4 |
slice=int(input("How many pizza slice you want"))
if slice%2==0
price=slice*120
print(price)
else
price=slice*123
print(price)
|
c61bb81014dba0334bb13516bd8044cc520bde54 | Williano/Solved-Practice-Questions | /MaleFemalePercentage.py | 1,308 | 4.1875 | 4 | # Script: MaleFemalePercentage.py
# Description: This program ask the user for the number of males and females
# registered in a class. The program displays the percentage of
# males and females in the class.
# Programmer: William Kpabitey Kwabla
# Date: 11.03.17
# Declaring the percentage v... |
3625e0b79a196fbe66833233114ebd5208b4e670 | Williano/Solved-Practice-Questions | /Object Oriented Programming/ProductionWorker.py | 1,254 | 4.09375 | 4 | # Script: ProductionWorker.py
# Description: This program creates an object from the ProductionWorker class in the
# Employee Class module. It is also a demonstration of python inheritance.
# Programmer: William Kpabitey Kwabla.
# Date: 05.03.17
# Importing the Employee class to allow access to it's data... |
dbaff76b1cd7e768f582828f609e937b493d774a | Williano/Solved-Practice-Questions | /RainfallStatistics.py | 3,869 | 4.40625 | 4 | # Module: RainfallStatistics.py
# Description: This program lets the user enter the total rainfall for each of
# 12 months into a list. The program then calculate and display the total
# rainfall for the year, the average monthly rainfall, and the months
# with the highest and low... |
2582a618219a2e0d3d43d30273d576a824303311 | Williano/Solved-Practice-Questions | /mass_and_weight.py | 1,791 | 4.71875 | 5 | # Scripts : mass_and_weight
# Description : This program asks the user to enter an object’s mass,
# and then calculates its weight using
# weight = mass * acceleration due to gravity.
# If the object weighs more than 1,000 newtons,
# it displays a message indicati... |
5086ee66505c76e27be7738c6022065c451771bb | Williano/Solved-Practice-Questions | /MultiplicationTable.py | 2,041 | 4.3125 | 4 | # Script: MultiplicationTable.py
# Description: This program ask for a number and limit and generates
# multiplication table for it.
# Programmer: William Kpabitey Kwabla
# Date: 20.07.16
# Defines the main function.
def main():
# Calls the intro function
intro()
# Declares variable for rep... |
9f23a7dc612e53ff01f96620978e8593ff9d8f82 | AngelMartinezC/Computational_Astrophysics | /Taller5/2_linear_interpolation.py | 1,513 | 3.59375 | 4 | #-*- coding: utf-8 -*-
"""
Computation of linear stepwise interpolation
"""
import numpy as np
import matplotlib.pyplot as plt
from interpolation import derivative as d
def f(x):
return np.array(1/(25*x**2 +1))
def linear(x,m=50):
point = len(x) -1
Y, X = [], []
x_tot = []
y_tot = []
for k in range(... |
ea5c2f10410e47894635107e2e3473b3fb7d5c19 | joooooooooooooooooooo/john | /hai.py | 150 | 4.125 | 4 | a=input("enter the number")
if (a>0):
print("it is a positive number")
elif a==0:
print(" it is a zero")
else:
print("it is a negative number")
|
cf532c058aaa3c2d329de4fd5d6c4ac9dc804a81 | msharaf1/Python | /BasicPythonFunctions/forLoopBasicII.py | 1,612 | 4.09375 | 4 | #1
""" def biggieSize(arr):
for i in range(0,len(arr)):
if arr[i] > 0:
arr[i] = "Biggie"
print (arr)
biggieSize([-3,-2,-1,3,4,5,7])
"""
#2.
"""
def countPositive(arr):
count = 0
for i in range(len(arr)):
if arr[i] >0:
count +=1
arr[len(arr)-1] = count
... |
63a9f0eca37613e7a9d36b0e0b1fd7178f628500 | kcsparks/osrs_highscores | /osrs_highscores/resources/utils.py | 900 | 3.703125 | 4 | import math
class OSRSXp:
"""OSRSXp
Class to encompass the math required for calculating xp for a specific level in OSRS.
"""
@staticmethod
def __calc(level):
"""calc
Calculates the xp difference for target xp of level.
Args:
level int: Target level to calcul... |
ebe619a2e7c7ffc05a6bc3186bed87d46b4ad526 | monaalomari99/firstpackage | /libmona.py | 2,338 | 3.5 | 4 | class MyClass:
def __init__(self):
pass
def return_max(self,args):
self.max=0
for i in range(0,len(args),1):
if args[i] > self.max:
self.max = args[i]
return self.max
def return_min(self,args):
self.min=0
for i in range(... |
04e834bfd4b0482a5d434fa8c11492feac017941 | embewee/webmining-ex4 | /libGeneral.py | 11,832 | 3.53125 | 4 | #! /usr/bin/python
# -*- coding: utf-8 -*-
import re
import os
import sys
import sqlite3
import operator
import extractor
import codecs
import math
'''
Removes special characters like '\n', '\s' etc from a given string
INPUT:
s: the string to remove the characters from
OUTPUT:
s: the string without spe... |
3af1b0e33c16aa328307b28db6c8116a74769a65 | alexeymakhortov/homework6-task-classes | /homework6.py | 4,154 | 4.03125 | 4 | class Animals: # общий класс животных
feed = 'голодный'
voices = 'Какой звук?'
def __init__(self, name, weight):
self.name = name
self.weight = weight # грамм
def food(self):
self.feed = 'накормлен'
def animal_sound(self, sound):
self.voices = sound
c... |
8cbe78e6ee1627ef260f63aa882c38994a0e470c | sunshinelala1991/leetcode | /reverseList.py | 1,068 | 3.609375 | 4 | # Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def reverseBetween(self, head, m, n):
"""
:type head: ListNode
:type m: int
:type n: int
:rtype: ListNode
"""... |
915c7300f5820f4db1fa71464a831d859b62827d | sunshinelala1991/leetcode | /totalHamming.py | 753 | 3.515625 | 4 | class Solution(object):
def totalHammingDistance(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums)==0 or len(nums)==1:
return 0
t=0
for i in range(len(nums)):
for j in range(i+1,len(nums)):
s1="{0:b}"... |
15949ac4b037c14628338c93f4efe38ef78b4fc8 | demoleas21/CrackingCodingQuestions | /src/Chapter 1/StringCompression.py | 593 | 3.5625 | 4 | """ 1.6 String Compression """
def compressor(string):
compression_table = {}
for key in string:
try:
compression_table[key] = compression_table[key] + 1
except:
compression_table[key] = 1
compressed_string = []
for key in compression_table:
compressed_s... |
4f685a3eb351eb995d979ef7279353600ee981da | koHd/learningPython | /ceaser.py | 1,194 | 3.953125 | 4 | import string
import argparse
alphabet = 'abcdefghijklmnopqrstuvwxyz'
punctuationSymbols = set(string.punctuation)
parser = argparse.ArgumentParser(description='Shift encrypt a plaintext file.')
parser.add_argument('-p', '--plaintext', help='Input plaintext file name', required=True)
parser.add_argument('-s', '--shif... |
afb7cbbcbd153db936e0d5acc14ac1c6be89b7a7 | Akarshit7/Python-Codes | /Coding Ninjas/Strings/Check Palindrome.py | 519 | 4.03125 | 4 | # Given a string, determine if it is a palindrome, considering only alphanumeric characters.
from sys import stdin
def isPalindrome(string) :
# Your code goes here
s = ""
count = 0
for l in string:
s = s + l
count = count + 1
r = ""
for i in range(count-1,-1,-1):
r = r +... |
eaf0b0cc73e4f0d10a0190169b21d07dd4ab0c09 | Akarshit7/Python-Codes | /Coding Ninjas/Two Dimensional Lists/Row Wise Sum.py | 395 | 3.78125 | 4 | # For a given two-dimensional integer array/list of size (N x M),
# find and print the sum of each of the row elements in a single line, separated by a single space.
p=int(input())
for i in range(p):
str=input().split()
n,m=int(str[0]),int(str[1])
arr=[]
for i in range(n):
b=input().split()
... |
596e39993129339fa272c671b82d43c35ccaf17e | Akarshit7/Python-Codes | /Coding Ninjas/Conditionals and Loops/Sum of even & odd.py | 284 | 4.15625 | 4 | # Write a program to input an integer N
# and print the sum of all its even
# digits and sum of all its odd digits separately.
N = input()
total = 0
evens = 0
for c in N:
c = int(c)
total += c
if c % 2 == 0:
evens += c
odds = total - evens
print(evens, odds)
|
873c7595a5c38befc5489e3805f430bf06efba8a | Akarshit7/Python-Codes | /Coding Ninjas/Introduction to Python/Rectangular Area.py | 381 | 3.828125 | 4 | # You are given a rectangle in a plane. The coordinates of one of its diagonals are provided to you. You have to print the total area of the rectangle.
# The coordinates of the rectangle are provided as four integral values: x1, y1, x2, y2. It is given that x1 < x2 and y1 < y2.
x1 = int(input())
y1 = int(input())
x2 =... |
e2d49bade4234f4d08806c738123bec0677b5c06 | Akarshit7/Python-Codes | /Coding Ninjas/Patterns 2/Pyramid Number Pattern.py | 416 | 3.671875 | 4 | # Print the following pattern for the given number of rows.
# Pattern for N = 4
# 1
# 212
# 32123
# 4321234
n = int(input())
i = 1
while i <= n:
spaces = 1
while spaces <= n - i:
print(" ", end="")
spaces = spaces + 1
j = i
while j > 0:
print(j, end="")
j = j - 1
... |
0bb4d9276fca919bdea6351726e0268839333529 | Akarshit7/Python-Codes | /Coding Ninjas/Arrays & Lists/Sort 0 1.py | 668 | 3.984375 | 4 | # You have been given an integer array/list(ARR) of size N that contains only integers,
# 0 and 1. Write a function to sort this array/list.
# Think of a solution which scans the array/list only once and don't require use of an extra array/list.
def sortZeroesAndOne(arr, n):
nxtzero = 0
for i in range(n):
... |
c2bd3cbe9df4bb5ce621a2acc22bcc30b0d8628d | Akarshit7/Python-Codes | /Coding Ninjas/Conditionals and Loops/Check number.py | 295 | 4.15625 | 4 | """
Given an integer n, find if n is positive, negative or 0.
If n is positive, print "Positive"
If n is negative, print "Negative"
And if n is equal to 0, print "Zero".
"""
n=int(input())
if n>=1:
print("Positive")
elif n == 0:
print("Zero")
elif n<=1:
print("Negative")
|
589ffff4cad218d08d53cf2e054f9d2d2a0b87f3 | Akarshit7/Python-Codes | /Coding Ninjas/Arrays & Lists/Pair Sum.py | 702 | 3.890625 | 4 | # You have been given an integer array/list(ARR) and a number X. Find and return the total number of pairs in the array/list which sum to X.
from sys import stdin
def pairSum(arr, n, x):
sum=0
for i in range(n):
for j in range(i+1,n):
if arr[i]+arr[j]==x:
sum=sum+1
retur... |
cbf2bac749cb2d877c50322d9f0e7b20c7f16ef2 | rektyyy/projects | /ArithmeticExamApplication.py | 2,482 | 3.78125 | 4 | import random
score = 0
all_equasions = []
def generate_easy():
symbols = ['+', '-', '*']
equasion_to_print = f'{random.randint(2, 9)} {random.choice(symbols)} {random.randint(2, 9)}'
equasion = equasion_to_print.split()
if '+' in equasion:
answer = int(equasion[0]) + int(equasion[2])
... |
7efda2be4c3fd2ba3070a31bfb0d913a9dfca433 | noey26/python | /operation_1.py | 538 | 3.65625 | 4 | ##변수 선언 부분(변수 초기화)
money, c500, c100, c50, c10 = 0, 0, 0, 0, 0
##메인(main) 코드 부분
money = int(input("교환할 돈은 얼마입니까?"))
c500 = money//500
money %= 500
c100 = money//100
money %= 100
c50 = money//50
money %= 50
c10 = money//10
money %= 10
print("\n 오백원짜리 ==> %d 개" %c500)
print(" 백원짜리 ==> %d 개" %c100... |
6435aa8340f2d1d66a76b68279ceb630461badbe | noey26/python | /week 2.py | 188 | 3.734375 | 4 | name = input('이름을 입력해주세요 : ')
print(name, "님 반갑습니다!")
age = input('나이를 입력해주세요 : ')
print("10년 후엔", int(age)+10, "살 입니다!")
|
4dfe380f00ab58f5741096abaf9493e869792cef | kelvDp/CC_python-crash_course | /chapter_5/toppings.py | 2,546 | 4.4375 | 4 | requested_topping = 'mushrooms'
# checks inequality: so if the req_topping is NOT equal to anchovies, then it will print the message
if requested_topping != 'anchovies':
print("Hold the anchovies!")
# you can check whether a certain value is in a list, if it is the output will be true, and if not --> false:
more... |
bf2d49f7af9f14f0800ba07aa7665f249944a613 | kelvDp/CC_python-crash_course | /chapter_8/TIY_8-7.py | 452 | 3.90625 | 4 | def make_album(name,title,songs=None):
album = {"artist_name":name,"album_title":title}
if songs:
album["songs"]= songs
return album
album1 = make_album("John","Music")
album2 = make_album("Jane","Classical")
album3 = make_album("Dave","Popping")
# you can also simply print the function since it ha... |
630e926f49514037051c98cded41250dc8c12f11 | kelvDp/CC_python-crash_course | /chapter_10/word_count.py | 929 | 4.4375 | 4 | def count_words(file):
"""Counts the approx number of words in a file"""
try:
with open(file,encoding="utf-8") as f:
contents = f.read()
except FileNotFoundError:
print(f"Sorry, but this file {file} does not exist here...")
else:
words = contents.split()
num_... |
17c8acde979e31854089ac390484e05079ebdbca | kelvDp/CC_python-crash_course | /chapter_6/TIY_6-11.py | 637 | 4.3125 | 4 | cities = {
"New York":{"country": "America", "population": 5000000, "fact": "Bill de Blasio is the mayor"},
"Amsterdam": {"country": "Netherland", "population": 850000, "fact": "Houses the Van Gogh Museum"},
"Johannesburg": {"country": "South Africa", "population": 957000, "fact": "Was home to Nelson Mandel... |
a17d084fd69edcb51ae61cd1f1ae58c5210b9310 | kelvDp/CC_python-crash_course | /chapter_11/names_test.py | 375 | 3.78125 | 4 | from chapter_11 import name_function as name
print("Enter 'q' at any time to quit.")
while True:
first = input("\nWrite your first name:")
if first == "q":
break
last = input("Write your last name:")
if last == "q":
break
formatted_name = name.get_formatted_name(first,last)
p... |
7950a6bc754171208fcfbde3e06e82f567b25525 | kelvDp/CC_python-crash_course | /chapter_16/sitka_highs_lows.py | 1,726 | 3.921875 | 4 | # We can make our informative graph even more useful by including the low
# temperatures. We need to extract the low temperatures from the data file
# and then add them to our graph, as shown here:
import csv
import matplotlib.pyplot as plt
from datetime import datetime
filename = "data/sitka_weather_2018_simple.csv"... |
fcefa167431b4e2efd08e9f95b43fb57cf3bd37b | kelvDp/CC_python-crash_course | /chapter_2/hello_world.py | 469 | 4.5 | 4 | #can simply print out a string without adding it to a variable:
#print("Hello Python World!")
#or can assign it to a variable and then print the var:
message= "Hello Python world!"
print(message)
#can print more lines:
message_2="Hello Python crash course world!!"
print(message_2)
#code that generates an error :
... |
e0429a2478d1f5751a722c25d7e932c3bec2e338 | kelvDp/CC_python-crash_course | /chapter_3/TIY_3-4.py | 263 | 3.625 | 4 | guest_list = ["Angela Yu" , "Jack Sparrow", "Michael Jackson"]
print(f"Dear {guest_list[0]}, I wouldd like to invite you for dinner.")
print(f"Dear {guest_list[1]}, I wouldd like to invite you for dinner.")
print(f"Dear {guest_list[2]}, I wouldd like to invite you for dinner.")
|
38dca7cdf402d16aff9d0c9e111598c449cf8e6a | kelvDp/CC_python-crash_course | /chapter_6/TIY_6-9.py | 307 | 4.03125 | 4 | favorite_places = {
"jack": ["croatia", "russia", "australia"],
"jill": ["canada", "brazil"],
"kelly": ["south africa", "new zealand"]
}
for name,locations in favorite_places.items():
print(f"{name}'s favorite locations are :")
for location in locations:
print(f"\t{location}")
|
59cdb01876a7669b21e7d9f71920850a2a88091c | kelvDp/CC_python-crash_course | /chapter_3/cars.py | 919 | 4.75 | 5 | cars = ['bmw', 'audi', 'toyota', 'subaru']
#this will sort the list in alphabetical order but permanently, so you won't be able to sort it back:
cars.sort()
print(cars)
# You can also sort this list in reverse alphabetical order by passing the
# argument reverse=True to the sort() method. The following example sorts... |
592f80cb6d4d07876dab963c33dd23d65bf1e254 | kelvDp/CC_python-crash_course | /chapter_4/TIY_4-5.py | 191 | 3.546875 | 4 |
numbers = list(range(1,1000000))
print(max(numbers)) #prints the largest nr
print(min(numbers)) #prints the smallest nr
print(sum(numbers)) #prints the sum of all the numbers inside range
|
9a6c01e73c78e5c039f7b4af55924e22b1d4ca85 | kelvDp/CC_python-crash_course | /chapter_4/dimensions.py | 542 | 4.21875 | 4 | dimensions = (200, 50)
#tuples are basically same as lists but they are immutable which means you can't change them without re-assigning the whole thing
print(dimensions[0])
print(dimensions[1])
print("\n")
#!!! cant do this : dimensions[0] = 250 !!!
#you can loop through them just like a list
#this is how to chan... |
08bac6f76746cdad48987433eab77754b54dcc7f | kelvDp/CC_python-crash_course | /chapter_6/TIY_6-8.py | 400 | 3.5625 | 4 | sarah = {"name": "sarah", "animal": "cat", "owner": "jack"}
spike = {"name": "spike", "animal": "dog", "owner": "dave"}
fluffy = {"name": "fluffy", "animal": "snake", "owner": "megan"}
tiny = {"name": "tiny", "animal": "dog", "owner": "donny"}
animals = [sarah, spike, fluffy, tiny]
for animal in animals:
print(f"... |
3db1874a875768b536dd17749d58c68813784504 | kelvDp/CC_python-crash_course | /chapter_5/TIY_5-5.py | 855 | 3.8125 | 4 | #version 1:
alien_color = "green"
if alien_color == "green":
print("You just earned 5 points.")
elif alien_color == "yellow":
print("You just earned 10 points.")
elif alien_color == "red":
print("You just earned 15 points")
else:
print("You didn't score anything...")
#version 2:
alien_color = "yellow"... |
629dcef31ce20bcdb60ab25fe0b6dd3b76412b9f | kelvDp/CC_python-crash_course | /chapter_10/number_writer.py | 285 | 3.65625 | 4 | import json
numbers = [2,3,5,7,11,13]
filename = "numbers.json"
with open(filename,"w") as f:
json.dump(numbers,f) # so dump the list numbers into f (numbers.json file)
# function takes two arguments: a piece of data to store and a file object it can use to store the data.
|
4f4dfbef399ebd99e02ec20a1fd130d4148f5de2 | kelvDp/CC_python-crash_course | /chapter_5/TIY_5-7.py | 388 | 4 | 4 | favorite_fruit = ["apple", "banana", "orange"]
if "apple" in favorite_fruit:
print("I really like apples!")
if "banana" in favorite_fruit:
print("I really bananas !")
if "orange" in favorite_fruit:
print("I really like oranges!")
if "strawberries" in favorite_fruit:
print("I really like strawberries!")... |
906a57cb5b9813652c9d66960ab30f157c769421 | kelvDp/CC_python-crash_course | /chapter_10/write_message.py | 1,615 | 4.84375 | 5 | # To write text to a file, you need to call open() with a second argument telling
# Python that you want to write to the file.
filename = "programming.txt"
with open(filename,"w") as file_object:
file_object.write("I love programming!")
# The second
# argument, 'w', tells Python that we want to open the file in ... |
8b8e585aba370fd45986148108e160f96571acbc | Nicolas-Theodoro/Comunica-o-entre-camadas-do-modelo-OSI | /CodificacaoCamadas.py | 1,587 | 3.5 | 4 |
class Aplicacao():
def __init__(self, mensagem):
self.protocolo = 'dns'
self.Mensagem = mensagem
self.Apresentacao = Apresentacao()
class Apresentacao():
def __init__(self):
self.protocolo = 'tcp'
self.Sessao = Sessao()
class Sessao():
def __init__(se... |
6fa5c6f470304b291762aa692d7a1f55529ef0d0 | Pnshimiye/News_Highlight | /app/source_test.py | 862 | 3.71875 | 4 | import unittest
from models import source
Source = source.Source
class SourceTest(unittest.TestCase):
'''
Test Class to test the behaviour of the Source class
'''
def setUp(self):
'''
Set up method that will run before every Test
'''
self.new_source = Source('ABC','ABC ... |
81fef05396e019b8c3bcb03e4a052401bdea58c4 | sudheersingampalli/Competetive-Coding | /LCS.py | 2,121 | 3.703125 | 4 | '''
Problem Description
Given two strings A and B. Find the longest common subsequence ( A sequence which does not need to be contiguous), which is common in both the strings.
You need to return the length of such longest common subsequence.
Problem Constraints
1 <= Length of A, B <= 1005
Input Format
First argument i... |
e527b2e1b6b219b5684f4b96c4c6ad822a5e01fc | sudheersingampalli/Competetive-Coding | /minJumpInSeats.py | 598 | 3.75 | 4 | '''
Solution: Bring the other persons to the middle person.
'''
class Solution:
# @param A : string
# @return an integer
def seats(self, A):
# start = arr[i]
# end = cp - mid + i
seating = [c for c in A]
c = seating.count('x')
print(seating, c)
arr = [-1]*c
j=0
for i in range(len(seating)):
if se... |
4ac2fb177772fdbfc6887021ac96aa5c17c77848 | sudheersingampalli/Competetive-Coding | /graphDFS.py | 2,247 | 3.875 | 4 | '''
Q1. Path in Directed Graph
Problem Description
Given an directed graph having A nodes labelled from 1 to A containing M edges given by matrix B of size M x 2such that there is a edge directed from node
B[i][0] to node B[i][1].
Find whether a path exists from node 1 to node A.
Return 1 if path exists else return 0... |
714fa30ff85c0287e591c72f5ea15d11f39b5a91 | sudheersingampalli/Competetive-Coding | /isValidBST.py | 729 | 3.765625 | 4 | # Definition for a binary tree node
import sys
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# @param A : root node of tree
# @return an integer
sys.setrecursionlimit(10*6)
def isValidBST(self, A):
return self.isValidBSTUtil(A, float('-inf'), float... |
3729c0ec2e06909cdbf65410e073bbeda8dd05b0 | sudheersingampalli/Competetive-Coding | /symmetricBT.py | 1,171 | 3.890625 | 4 | '''
Q1. Symmetric Binary Tree
Solved
feature icon
Using hints is now penalty free
Use Hint
Problem Description
Given a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).
Problem Constraints
1 <= number of nodes <= 105
Input Format
First and only argument is the root node of the b... |
97eaa1137bef0a9ab68432941c47ea9c30b88230 | sudheersingampalli/Competetive-Coding | /FindPathWithSumKInBT.py | 756 | 3.65625 | 4 | # Definition for a binary tree node
'''
Given a BT, find if a path exists such that the sum from root to leaf equals to k
'''
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
import sys
class Solution:
# @param A : root node of tree
# @param B : integer
# @return an inte... |
18fae817f1bf7c8d2d8f2389da27e95dd4a11726 | sudheersingampalli/Competetive-Coding | /IdenticalBT.py | 622 | 3.640625 | 4 | '''
Check if two trees are identical or not
'''
# class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# @param A : root node of tree
# @param B : root node of tree
# @return an integer
def isSameTree(self, A, B):
def helper(A, B):
if A ... |
a24039acf7851b57d90750e277ddb8cae16244bb | Messi-Q/Coursera-ml-class-ex | /linear_regression/linear_regression.py | 4,409 | 3.5 | 4 | # -*- coding:utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# load data from file
def load_data(filename):
data = []
file = open(filename)
for line in file.readlines():
linearr = line.strip().split(',')
col_num = len(linearr)
te... |
8f732d671d158a32dfa7e691f588bef489b74ae8 | beffiom/Learn-Python-The-Hard-Way | /ex6.py | 1,204 | 4.71875 | 5 | # initializing a variable 'types_of_people' as an integer
types_of_people = 10
# initializing a variable 'x' as a formatted string with an embedded variable
x = f"There are {types_of_people} types of people."
# initializing a variable 'binary' as a string
binary = "binary"
# initializing a variable 'do_not' as a strin... |
6e6dfc1868f174f705b813251561da3b07057393 | cutiebananaface/Thesis-code | /mylength_py.py | 1,696 | 3.8125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Feb 7 13:39:01 2020
@author: rodri
"""
import numpy as np
import operator as op
def mylength(v, axis1=None):
length= np.size(v, axis=None)
if type(v) is dict:
length=len(v)
return length
def findnonzeros(v, comparing_val=0, operator_fx= o... |
daaff821bf0876c567b9d8a54c855e669356cb5f | taiyang0725/python | /Dome4.py | 10,518 | 3.671875 | 4 | #****************a三目运算符*********
'''
a='hello'
b='world'
c=True and a or b
print c
d=False and a or b
print d
strs='a.s.d.f.g.h.j.j.k'
print strs.join('pp')
print repr("hello,world!")#创建字符窜
print str("hello,world!")#转化为合理字符串
'''
#***************检验一个值是否存在次序列*********
'''
database=[['a','1'],['b','2'],['c','3'],['d','4... |
281e3291fb8c7adb2695c66ff5bc1c69ad0eedce | hongyong3/TIL | /Algorithm/문제/수업/D-13t/AD/[TST] 숫자 찾기 (이진탐색).py | 559 | 3.546875 | 4 | import sys
sys.stdin = open("[TST] 숫자 찾기 (이진탐색)_input.txt", "r")
def binary_search(a, key):
start = 0
end = len(a) - 1
while start <= end:
middle = (start + end) // 2
if key == a[middle]: # 검색성공
return middle + 1
elif key < a[middle]:
end = middle - 1
... |
411de74beb38e499191e18d32efa50d2236faa14 | hongyong3/TIL | /Algorithm/Swea/D3_4522.py | 369 | 3.625 | 4 | import sys
sys.stdin = open("D3_4522_input.txt", "r")
T = int(input())
for test_case in range(T):
data = str(input())
result = "Exist"
for i in range(int(len(data) / 2)):
if data[i] == "?" or data[len(data) - 1 - i] == "?":result
elif data[i] != data[len(data) - 1 - i]:result = "Not exist"
... |
d312082fdbd29fa5810d3495ecc4ca149b61e99a | hongyong3/TIL | /Algorithm/문제/수업/D-01/BubbleSort.py | 604 | 4.03125 | 4 | def bubblesort(data):
for i in range(len(data)-1, 0, -1): # 1 2 3 4
for j in range(0, i): # 1 2 3 4
if data[j] > data[j+1]: # 오름차순
data[j], data[j+1] = data[j+1], data[j]
data = [55, 7, 78, 12, 42]
bubblesort(data)
print(data)
def bubblesort(data):
... |
846f276694caee1befa88a869c020dfc63290f2a | hongyong3/TIL | /Algorithm/Swea/Line_test5.py | 491 | 3.53125 | 4 | import sys
sys.stdin = open("Line_test5_input.txt", "r")
def factorial(num):
fac = 1
for n in range(1, num+1):
fac *= n
return(fac)
N, M = map(int, input().split())
x, y = map(int, input().split())
data = [[0] * N for _ in range(M)]
data[x][y] = 1
ans1,ans2 = 0, 0
if x < 0 or x >= N or y < 0 or ... |
9b4e35d80c5159aa712cc268bc7a7739cc4a3d8a | hongyong3/TIL | /Algorithm/문제/수업/D-03/2차원배열_순회.py | 604 | 3.828125 | 4 | array = [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]]
# i : 행의 좌표, n = len(array)
# j : 열의 좌표, m = len(array[0])
# 행 우선
for i in range(len(array)):
for j in range(len(array[i])):
print(array[i][j], end = " ")
print()
print()
# 열 우선
for j in range(len(array[0])):
for i in range(len(array)):
... |
be5a551a4be296b187e7ae326105700e41af688c | hongyong3/TIL | /Algorithm/Swea/D1_6223.py | 210 | 3.921875 | 4 | class Circle:
def __init__(self, radius):
self.__radius = radius
def area(self):
return "원의 면적: {}".format(3.14 * pow(self.__radius, 2))
circle = Circle(2)
print(circle.area()) |
bdcfbf051d722ab3386f8fd950f8e58792854293 | RadiX-PY/algorithmic-paradigm | /Fibonacci ( Dynamic Programming ).py | 467 | 3.90625 | 4 | # Dynamic Programming Fibonnaci Method
from timeit import default_timer as timer
start = timer()
F = [-1]*500 #array to store fibonacci terms
def dynamic_fibonacci(n):
if (F[n] < 0):
if (n==0):
F[n] = 0
elif (n == 1):
F[n] = 1
else:
F[n] = dynamic_fibonacci(n-1) + dynamic_... |
c596386b5302cedf873c371b2691c20f017bd803 | JakeJewsbury/hello-world | /int if elif test.py | 140 | 3.890625 | 4 | print('Please type your age.')
age = input()
if age != int:
print('Please use numbers.')
else age == int:
print('Thank you.')
|
d568c71f8811b6ff9b0f7043c0025c5ada530105 | mattlaguardia/py-timer | /timer.py | 321 | 3.90625 | 4 | # A SIMPLE TIMER IN PYTHON #
import time
seconds = input ("Number of Seconds: ")
startTime = time.time()
finishTime = startTime + seconds
while time.time() < finishTime:
print seconds
seconds = seconds -1
time.sleep(1)
print "Time is up!" * 4
import sys
sys.stdout.write('\a\a\a\a')
sys.stdout.flush()... |
7aea346171c0d4207cdb46c3186918d92a144e11 | lulacoco/Programming-Platforms-Learning | /Lab_8/Main.py | 3,422 | 3.765625 | 4 | from functools import reduce
import collections
from collections import defaultdict
def increment(iterable):
result = list(map(lambda x: x+1, iterable))
print(result)
def product(string_of_numbers):
result = reduce((lambda x, y: x * y), string_of_numbers)
print(result)
def reduce_non_alpha(s):
... |
21b262f5e93129d424b2643cc7459f66716be120 | yufeng97/CSSE1001_Assignments | /Assignment2/stocks.py | 7,972 | 3.953125 | 4 | """
Classes used in the second assignment in CSSE1001.
StockCollection: All stock market data stored in application.
Stock: Data for a single stock.
TradingData: Data for a single day of trading in one stock.
Loader: Abstract class defining the process of loading stock market data.
Analyser: Ab... |
ec3a54def3eb9ffbc537417d748cc41f13711d47 | cillian64/2manybricks | /brick.py | 1,561 | 3.6875 | 4 | import pygame
import os
class Brick:
def __init__(self, rect, colour, life, multiball=False, invert=False):
"""
rect is a pygame rect describing my position and size.
colour is a tuple of (red, green, blue)
life is my number of life-points!
"""
self.multiball = mult... |
b2ba1bc72afca24eac938a13c14e7ac5f1a33e22 | ThaiSonNguyenTl/NguyenThaiSon-Lab-c4e24 | /lab3/homework_lab3/seri_ex9.py | 202 | 3.703125 | 4 | def get_even_list(l):
new_l = []
for i in range(len(l)):
if (l[i]% 2 == 0):
new_l.append(l[i])
return new_l
# l = [1,4,5,-1,10]
# test_l = get_even_list(l)
# print(test_l) |
2f4f619e5366ea374ee53ed20b6039346f67fddb | arrzdev/KahootBot | /logreader.py | 183 | 3.5 | 4 | last = ''
while True:
with open('logs.txt', 'r') as f:
last_line = f.readlines()[-1]
if last_line != last:
print(last_line)
last = last_line
|
1244ebcc03374f0ff37b1e82fc3cc72deee03148 | Larc-Asgard/LPTHW | /ex29/ex29.py | 436 | 3.9375 | 4 | people = 20
cats = 30
dogs = 15
if people < cats:
print "Too many cats, not enough slaves."
if people > cats:
print "Enough slaves!"
if people < dogs:
print "There are more dogs than men."
if people > dogs:
print "There are more dawg than dogs."
dogs += 5
if people >= dogs:
print "People >= Do... |
a31a24a046bb325c5436f4b0f829b80285b14af6 | Larc-Asgard/LPTHW | /ex14/ex14.py | 541 | 3.609375 | 4 | # -*- coding: utf-8 -*-
from sys import argv
script, user_name = argv
prompt = "Input:"
print "HI %s, I'm the %s script:"%(user_name, script)
print "Here is a few questions for you, %s"% user_name
print "Please input your opinion toward Python or programming"
like = raw_input(prompt)
print "Please input your locat... |
cd1e137d53325fcd2f7084654877b0c10646ae40 | sitaramsawant2712/Assessment | /python-script/problem_1_solution_code.py | 926 | 4.34375 | 4 | """
1. If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9.
The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000.
(Answer: 233168) (solution code attached: problem_1_solution_code.py)
"""
def natural_number_multi_three_and_five(low... |
3de0803323695cabbeca0f3ecf0e98242a0e2c5c | MazenMohamed811/Log-in | /LOGIN SYSTEM FINAL.py | 1,131 | 3.890625 | 4 | def Register():
hand=open("users.txt","a")
print ("--------------")
print ("Registration")
print ("--------------")
users=input("Enter your username : ")
passes=input("Enter your password : ")
hand.write(users+"\t"+passes+"\n")
hand.close()
def login():
print ("--------------")
... |
66190c933458d55375005fc56ec8ad9bf20a39e4 | LuisUchoa/Logic_programming---Python | /aula03.py | 295 | 3.953125 | 4 | #Laços de Repetição + Listas
for palavra in range(1,4):
print('Carrengado')
'''
for item in coleção:
espressão
'''
for item in range(1,21):
print(item)
for item in range(1,20,2):
print(item)
nomes = ['Luis','Uchoa','Felipe']
for nome in nomes:
print(nome) |
0e2ced45c89f2df9793b8922f31cbf3ee6c6c579 | anisdube1/Artificial-Intelligence-project | /Othello/moves.py | 2,392 | 3.71875 | 4 | from board import *
from Othello import print_board
class move:
def __init__(self, x, y):
self.x = x
self.y = y
self.v = -1
def min_value(color, board, limit):
if(color == 'w'):
m_color = 'b'
else:
m_color = 'w'
if(limit == 0):
ans = count(board, 'b') - c... |
705f9b9b642f5979bdbedeb104a601310107f406 | lcsavb/python-520 | /estudo/practicepython/lesson5.py | 528 | 3.859375 | 4 | # Achar a intersecção entre duas listas, sem valores repetidos.
import random
#
# a = set([1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89])
# b = set([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13])
#
#
# print(a & b)
#Gerar duas listas randômicas para testar a solução encontrada.
lista1 = []
lista2 = []
for n in range(300):
... |
3755a33915b0a0053a9124456c9c5d3960170228 | lcsavb/python-520 | /aula1/experiments.py | 615 | 3.859375 | 4 |
def crazysum (number1):
i = 0
while i <=number1:
i = i + 1
return i
print (crazysum(10))
# variáveis / verificar tipo de variável tipagem dinâmica
GRAVIDADE = 9.8
primeiro_nome = 'Lucas'
segundo_nome = 'Amadeus'
ultimo_nome = 'Xavier'
idade = 25
idade = '25'
professor = True
variavel = 'string'
print(ty... |
e6798b5f38a92301c4cec918ccb84206c10906d9 | Tidy-Bear/ML-Lab | /Lab01-03.py | 241 | 3.796875 | 4 | def printStars(s):
for i in range(len(s) + 3):
print(chr(0x2605), end="")
print("")
if __name__ == "__main__":
s = "我喜欢数据科学导论"
printStars(s)
print(chr(0x2605), s, chr(0x2605))
printStars(s)
|
7e8a81ba26f35e137d15ccbf1702a84fc59bcbf7 | priyanshkulshrestha/CSI-SIG-Python | /Module 3/Q3 GCD.py | 314 | 3.75 | 4 | # Name Priyansh
# roll no. 1900300100165
print("Enter two number for finding GCD")
n1 = int(input("Enter the first number : "))
n2 = int(input("Enter the second number : "))
i = 1
gcd = 1
while i<=n1 and i <=n2:
if (n1%i == 0 and n2%i == 0):
gcd = i
i += 1
print(f"G.C.D. of {n1} and {n2} : {gcd}") |
06fe035378b977f5dc7e1912dbdd9a57c6623cde | priyanshkulshrestha/CSI-SIG-Python | /Module 7/01mul.py | 155 | 3.65625 | 4 | print("Priyansh")
print("1900300100165")
def mulist(a):
mul = 1
for i in a:
mul *= i
return mul
v = [1,2,3,4,5]
print(mulist(v))
|
19299c6847c15db5d0c776bbabb091fa2bfa2ca5 | priyanshkulshrestha/CSI-SIG-Python | /Module 4/Q2 Digit sum.py | 221 | 3.671875 | 4 | print("Priyansh")
print("1900300100165")
num = input("Enter any number: ")
l = len(num)
sum = 0
i = -1
while(i>=-l):
# print(num[i])
sum += int(num[i])
i -= 1
print (f"sum of all digit of given number: {sum}") |
3962d068eb981fdf1bd770e1b7c6086f6d115dd4 | priyanshkulshrestha/CSI-SIG-Python | /Module 5/Q2 listelelen.py | 193 | 3.75 | 4 | print("Priyansh")
print("1900300100165")
li = ["Priyansh","Kulshrestha","prateek","nihir","akash"]
long =0
for i in li:
long = max(long,len(i))
print(f"length of the longest word = {long}") |
1e19e559c0b05629da03e82dacaf3bf925aa9d7e | kundanjha1076/new-python-cours | /string.py | 232 | 4.1875 | 4 | name="kundan "
age=19
print("hello {} your age is {}".format(name,age))#.format method
#f method
print(f"hello {name} your age is {age}")
print(len(name))
x="kundan kumar jha"
y=x.upper()
print(y)
a="kundan kumar jha"
print(a.replace("kundan","kiran")) |
d5cbc72eaefa588eaec8fbd36ee442c35f574425 | MarekFabinski/algorytmy_i_struktury_danych | /anagram.py | 579 | 3.703125 | 4 | def main():
def anagram(word1, word2):
n = len(word1)
if n != len(word2):
return False
slownik1 = dict()
slownik2 = dict()
for i in range(n):
if word1[i] in slownik1:
slownik1[word1[i]] += 1
else:
slownik1[wo... |
8d498e582bc84115a724d04de93593ecc84f14da | pchtsp/UdacityStackFound | /examples/update_data.py | 1,196 | 3.734375 | 4 | from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from database_setup import Base, Restaurant, MenuItem
engine= create_engine('sqlite:///restaurantmenu.db')
Base.metadata.bind= engine
DBSession= sessionmaker(bind= engine)
session= DBSession()
#how to use a session:
#newEntry= ClassName(pro... |
e8aef8673d7a10a7e04b489d0e9d037fd19b5e0a | Paziwaz/exercism | /python/word-count/word_count.py | 251 | 3.625 | 4 | import re
import collections
def word_count(phrase):
words = re.split("[^0-9a-zA-Z']", phrase.lower())
words = list(filter(lambda word: word, words))
words = map(lambda word: word.strip("''"), words)
return collections.Counter(words)
|
656515343cf98224a29ae1a90ded2d7e1285296e | PreethiPrakashA/hackerrank | /problem-solving/Set .intersection() Operation.py | 202 | 3.6875 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
int(input())
x = set(map(int,input().split()))
int(input())
y = set(map(int,input().split()))
z = x.intersection(y)
print(len(z))
|
5c7db16bc3c88293b3f3edf7e93f36bb0f520ece | Darya2021/pythonclass | /Python-2-Homework1.py | 1,001 | 3.890625 | 4 | # Tamrine mashin hesab, 2 adad vorodi ra gerefte va amale riazi ra anjam dahad.
number_1= float(input("B narmafzare mashinhesab khosh amadid. \nlotfan adade \
aval ra vared konid: \n"))
number_2= float(input("lotfan adade dovom ra vared konid: \n"))
operator= input("lotfan amalgare riazi ra vared konid: \n+ jame, - ta... |
5e3246d93a289015c9ba699382dc4d327620c393 | ailadson/notes | /algorithms/graphs/code/reverse_perfect_bt.py | 1,277 | 3.578125 | 4 | def reverse_perfect_bt(node, to_reverse = True):
if node.right_child is None:
return
if to_reverse:
r_child = node.right_child
l_child = node.left_child
node.right_child, node.left_child = l_child, r_child
r_child.right_child, l_child.right_child = l_child.right_child, r_... |
88b75f6dd82227870ffc29e8a952994bbfd70108 | ailadson/notes | /algorithms/geometry/code/area_of_tri.py | 321 | 3.828125 | 4 | def area_of_tri(a,b,c):
ax, ay = a.x, a.y
bx, by = b.x, b.y
cx, cy = c.x, c.y
return (ax*by - ay*bx + ay*cx - ax*cy + bx*cy - by*cx)/2.0
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
if __name__ == '__main__':
print area_of_tri(Point(0,0), Point(0,5), Point(5,0))... |
45d797bb953f44166527095ad6aaea0e3f2e81d9 | ailadson/notes | /algorithms/dp/code/subset_equal_total.py | 972 | 3.65625 | 4 | def subset_equal_total(arr, total):
mat = build_mat(arr, total)
for i in range(1, len(mat)):
for j in range(1, total + 1):
mat[i][j] = is_equal_subset(mat, arr, i, j)
subset = find_subset(mat, arr)
subset.reverse()
return subset
def build_mat(arr, total):
mat = [[False] * (... |
de380b259a6c6e922ec1d7e3786aed82955e2f82 | ytian25/myEE551project | /TetrisGame/screens.py | 3,887 | 3.625 | 4 | import pygame
import time
from settings import *
from functions import judge,dock
def print_screen_text(screen, font, x, y, text, fcolor=(255, 255, 255)):
imgText = font.render(text, True, fcolor)
screen.blit(imgText, (x, y))
def display_screen(screen,pause,start,font1,font2,font_pos_x,font1_height,g... |
cc7a50c93dded63e648a1e0f3c627cf0e490b207 | OngZhenHui/Sandbox_Prac3 | /ascii_table.py | 1,054 | 4.1875 | 4 | def main():
character = str(input("Enter a character: "))
print("The ASCII code for {} is {}".format(character, ord(character)))
lower_limit = 33
upper_limit = 127
number = get_number(lower_limit, upper_limit)
print("The character for {} is {}".format(number, chr(number)))
for i in range(... |
d187c15ce69b07f91f17f10f6c92f62b77124e67 | slevinsps/python_prog | /python_labs/tkinter/vipukl_4xugol.py | 4,053 | 3.640625 | 4 | # Спасенов Иван ИУ7-13
# Выписать точки, области которых находятся остальные точки
from tkinter import *
from math import sqrt
def udalenie(a):
b = True
while b:
for i in a:
if a.count(i)!=1:
a.remove(i)
break
b = False
# Функция... |
fe6b90d4f766c6f1993dbeeee2a2f4c89c4a291b | slevinsps/python_prog | /python_labs/интегралы/integral2.py | 1,320 | 3.859375 | 4 | # Спасенов Иван ИУ7-13
# Вычисление интегралов методом правых прямоугольников с заданной точностью
# Функция
from math import *
def f(x):
g = x*x
return g
# Метод правых прямоугольников
def int_right(a,b,n):
h=(b-a)/n
s = 0
for i in range(1,n+1):
x = a+i*h
s += f(x)*... |
0470df03d30235319bc344eaeac70a049601ba6c | slevinsps/python_prog | /python_labs/файлы/FileCreator1.py | 5,942 | 3.9375 | 4 | # Спасенов Иван ИУ7-13
# Работа с файлами
while True:
name = None # имя файла
# Начальное меню
print('Для хранения базы данных игр вам нужен текстовый файл')
print('''
1 - Создать новый файл
2 - У меня уже есть файл
0 - Выход
''')
q = int(input('Ввведите пункт меню: '))
i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.