blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
43b9cdffc352e3ea5465ba5b5ad4f450ac9e2dfe | Ankityadav200/python_course | /day4/handson.py | 1,357 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Feb 26 16:29:29 2019
@author: ankit
"""
# Hands On 1
# Print all the numbers from 1 to 10 using condition in while loop
n=1
while(n<=10):
print(n)
n=n+1
# Hands On 2
# Print all the numbers from 1 to 10 using while True loop
n=1
while(True):
print(n)
n... |
44a1f074995d5007d0fcd834abd0cbe19104f950 | LIMMIHEE/python_afterschool | /Code05-11.py | 589 | 3.84375 | 4 | select, answer, numStr, num1, num2 = 0,0,"",0,0
select = int(input("1 입력한 수식 계산 2. 두 수 사이의 합계" ))
if select==1 :
numStr=input(" *** 수식을 입력하세요 " )
answer = eval(numStr)
print("%s 결과는 %5.1f입니다" % (numStr,answer))
elif select==2:
num1 = int(input("** 첫번째 숫자 입력 : "))
num2 = int(input("** 두... |
dfe7f6ab7e03975f8b11e797cba8ea9d697381d6 | marcelinofavilla/URI | /1008.py | 131 | 3.71875 | 4 | F = int (input())
H = int (input())
S = float (input())
print("NUMBER = "+str(F))
print("SALARY = U$ {:.2f}".format(round(H*S, 2))) |
8ed258aa509a614ea42e1c1a1d9a581386c06901 | Benga22/CS2302-LAB1- | /Lab8.py | 3,251 | 3.859375 | 4 | # Course Name: CS2302
# Author: Olugbenga Iyiola ID:80638542
# Assignment 8
# Instructor: Olac Fuentes
# T.A.: Nath Anindita / Maliheh Zargaran
# Date of last modification: 05/10/2019
# Purpose of program: Binary Search Trees
# importing all modules needed to run the program
import random
from mpmath import ... |
aaefc76e357d9941a7858a4fdbf0b62b369bacd8 | averjr/Python-playground | /codewars/codewars_31.01.py | 669 | 3.8125 | 4 | import math
def sum_dig_pow(a, b):
# range(a, b + 1) will be studied by the function
# your code here
result = []
for d in range(a, b+1):
flag = False
digits_count = len(str(d))
summ = 0
for i in range(0, digits_count):
current_digit = int(str(d)[i])
... |
37c131508dc7c8006df45fb6f2de75f7b904cf8f | kriananya/Calender | /calender.py | 111 | 3.59375 | 4 | import calendar
year = 2021
#month = 12
#print(calendar.month(year,month))
print(calendar.calendar(year))
|
69212ca09fd578de1ee237fc413add1515a95a5e | zsXIaoYI/Python_Daily | /cn/zsza/oop/operatorr/ol/_1_getitem.py | 1,108 | 3.640625 | 4 | # !/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time: 2020/2/18 17:06
# @File: _1_getitem.py
# __author__ = 'zs'
class Number:
def __init__(self, start):
self.data = start
def __sub__(self, other):
return Number(self.data - other)
X = Number(5)
Y = X - 2
print(Y.data)
class Indexer:
... |
1a6e1a198428befb6428a8ba499167779fefb37f | zhuny/Codejam | /solution/U/UX/ConsecutivePrimes/__main__.py | 1,109 | 3.890625 | 4 | def get_int():
return int(input())
def get_line():
return input().strip()
def get_ints():
return [
int(i)
for i in input().split()
]
def sqrt(n):
x = n // 2
for i in range(100):
x = (x*x + n) // (x*2)
if x*x <= n:
return x
else:
return x-1
... |
6edeb38bfc2ac7e625519e32cbd4d31ac0066fff | Dcon1/flasktryout | /Prac-2/numbers.py | 294 | 3.703125 | 4 | #file = open("numbers.txt", mode="r")
#line_one = int(file.readline())
#line_two = int(file.readline())
#print(line_one + line_two)
#file.close()
file = open("numbers.txt", mode="r")
total = 0
for line in file:
number = int(line)
total += number
print(total)
file.close() |
de4371f228fb33d729e80cf01ed8256ead69787b | devwill77/Python | /Ex019.py | 433 | 4 | 4 | '''
- DESAFIO 019
- Um professor quer sortear um dos seus quatro alunos para apagar o quadro.
Faça um programa que ajude ele , lendo o nome deles e escrevendo o nome do escolhido.
'''
from random import choice
a1 = str(input('Aluno 1: '))
a2 = str(input('Aluno 2: '))
a3 = str(input('Aluno 3: '))
a4 = str(input('Aluno 4... |
dd22165aca136bc981605cb9866348d323b878f0 | sankeerth/Algorithms | /DynamicProgramming/python/leetcode/edit_distance.py | 2,474 | 4.125 | 4 | """
72. Edit Distance
Given two words word1 and word2, find the minimum number of operations required to convert word1 to word2.
You have the following 3 operations permitted on a word:
Insert a character
Delete a character
Replace a character
Example 1:
Input: word1 = "horse", word2 = "ros"
Output: 3
Explanation:
h... |
f7b84823364139ba5f5bc11bc98b3c66bacd6e21 | JJink/python_lecture | /triangle_area.py | 376 | 4.125 | 4 | def triangle_area() :
width = float(input("밑변 길이: "))
height = float(input("높이 : "))
TA = (width * height)*(1/2)
return(TA)
print(triangle_area())
def area_circum():
radius = float(input("원의 반지름을 입력하세요 : "))
area = radius * radius * 3.14
circum = 2 * radius * 3.14
return area, circum... |
7d2e0d39843a2a2c7e105f18bc1a0ce11d2f74ba | a413107719/crawler | /Scrapy框架练习/bmw/工具.py | 442 | 3.78125 | 4 | # -*- coding: utf-8 -*-
import os
# 不传值默认返回当前路径,传入几返回上几层(绝对路径)
def os_path_dirname(file,num=0):
# file 为你使用该函数时的__file__
# 循环版
# start = file
# for i in range(num):
# start = os.path.dirname(start)
# return start
# 递归版
start = file
if not num:
return start
return os... |
5ddeb140aaefefd6647611f2b31b51daf251375b | Athenian-ComputerScience-Fall2020/functions-practice-21ccronk | /multiplier.py | 598 | 4.46875 | 4 | '''
Adapt the code from one of the functions above to create a new function called 'multiplier'.
The user should be able to input two numbers that are stored in variables.
The function should multiply the two variables together and return the result to a variable in the main program.
The main program should output the ... |
c00debac287706dd17be22c366c06a931bb649c3 | adqz/interview_practice | /leetcode/sample.py | 208 | 3.546875 | 4 | # 3. Debugging loops
names = ['David Wallace', 'Jim Halpert', 'Michael Scott', 'Dwight K. Schrute']
numSpaces = 0
for i in range(len(names)):
name = names[i]
for char in name:
if char == ' ':
numSpaces += 1
names = [] |
2cbd8c5623c49a0f11fe14d7200e617263315961 | markosolopenko/python | /leetcode/binary_tree/diiferent_task_with_binary_tree/insert_into_bst.py | 921 | 3.953125 | 4 | from leetcode.binary_tree.diiferent_task_with_binary_tree.diameter_of_binary_tree import TreeNode
class Solution:
def insert_into_bst(self, root: TreeNode, value: int) -> TreeNode:
if root is not None:
if root.val > value:
if root.left is None:
root.left = T... |
008c406bfe88327850ca8ef71e022f580b7f915f | AlexandertheG/crypto-challenges | /set_2/PKCS7_padding_validation.py | 536 | 3.625 | 4 | import sys
import binascii
def padding_valid(in_str):
pad_lngth = int(binascii.hexlify(in_str[len(in_str)-1]), base=16)
valid_pad = True
for i in range(0, pad_lngth):
if int(binascii.hexlify(in_str[len(in_str) - pad_lngth + i]), base=16) != pad_lngth:
valid_pad = False
break
return valid_pad
str_invalid ... |
b394244adbd306b81b19e8d5d474a739a21e32c0 | jacebrowning/mine | /mine/models/config.py | 3,849 | 3.65625 | 4 | """Data structures for all settings."""
from dataclasses import dataclass, field
import log
from .application import Application
from .computer import Computer
@dataclass
class ProgramConfig:
"""Dictionary of program configuration settings."""
computers: list[Computer] = field(default_factory=list)
ap... |
d2af18b6654365b8355d0fa534acf6472dee1509 | lili-n-f/Nobrega-Liliana-2021-2 | /Hangman.py | 3,082 | 3.734375 | 4 | from Game import Game
class Hangman(Game):
def __init__(self, requirement, name, award, rules, questions):
super().__init__(requirement, name, award, rules, questions)
def game_begins(self, player):
self.choose_random_question()
self.define_current_clues()
wi... |
a56b729820877411a9cb1e8b1622d7ffc93ca37d | systemquant/input_reader | /input_reader/input_reader.py | 4,907 | 3.71875 | 4 | # -*- coding: utf-8 -*-
from __future__ import division, print_function, unicode_literals
from .key_adder import _KeyAdder
from .helpers import ReaderError, SUPPRESS
from .py23compat import py23_basestring
__all__ = ['InputReader', 'ReaderError', 'SUPPRESS']
class InputReader(_KeyAdder):
"""\
:py:class:`Inp... |
8b26463d454cfc49feb7e0b928c50ebee533593e | westgate458/LeetCode | /P0240.py | 4,072 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Aug 13 14:26:01 2019
@author: Tianqi Guo
"""
class Solution(object):
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
# Solution 1 beats 99.66%: binary search on e... |
912ebda738029d5c6f333311e6d9ca9f7e25b8e3 | meryemmhamdi1/Gokcen_Meryem_Riyadh_ADA | /03 - Interactive Viz/university_canton_mappings.py | 1,078 | 3.53125 | 4 | import requests
import json
def get_canton_id(google_url, university):
"""
Getting the canton corresponding to university
:param university:
:return:
"""
json_data = requests.get(google_url, params={"address": university}).json()
# We try to return the first result with 'administrative... |
dd67e11094912546608dcf08689781b1ccb9fc80 | lhwisdom07/ball_Filler | /ball_filler.py | 391 | 3.796875 | 4 | import math
numberofB =int(input ("How many bowling balls will be manufactured? "))
ballD = float(input ("What is the diameter of each ball in inches? "))
ballR = float(ballD / 2)
coreV = int(input("What is the core volume in inches cubed? "))
fillerA = (4/3) * (math.pi * (ballR ** 3))- coreV
print("You will need",fil... |
fa223d47df64573b11f3e77a8ac3ae5381cbad34 | KendrickAng/competitive-programming | /kattis/merge-k-sorted-lists/merge-k-sorted-lists.py | 989 | 3.75 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
if not lists:
return None
h = []
... |
7c752f43e9f730690e5234b20633fec1167102dd | Padfoot7577/PSetBuddy | /individual_vectors.py | 1,517 | 3.671875 | 4 | """
This method takes a 2*2 matrix (nested lists).
the last column of the list represent all the classes each person takes
step 1: loop through each person's classes, add it in the set
step 2: make the set into a list, sort the list
step 3: check each person's classes against the master list, create vector
with 1s bein... |
4087d93f025eb0b45693e6745523a56d650f76fe | haokr/PythonProgramming_Advanced | /chapter5_customSequence/bisect_test.py | 417 | 3.765625 | 4 | import bisect
from collections import deque
# 用来处理已排序的序列,用来维持已排序的序列(升序)
# 二分查找
#inter_list = []
inter_list = deque() # 只要是可变的序列类型就可以
bisect.insort(inter_list, 3)
bisect.insort(inter_list, 2)
bisect.insort(inter_list, 6)
bisect.insort(inter_list, 4)
bisect.insort(inter_list, 5)
print(inter_list)
print(bisect.bisect(in... |
3592dbff6c3c7c1e9b074204000eb710d4caed9c | dmaher1890/Hangman | /Hangman.py | 1,385 | 4.15625 | 4 | import random
#Welcome to the game
print ("Welcome to David's HangMan Game")
#Word Choosen
words = ["hangman", "program", "python", "mountain", "family", "lighthouse", "recover", "news", "puzzle", "birthday"]
word = random.choice(words)
count = len(word)
print("The word has", count, "letters")
#split the... |
3c97e2850a906c7915568c637616fc251e5e2ed9 | dongndp/my-hkr | /python/nestedlist.py | 830 | 3.96875 | 4 | '''
https://www.hackerrank.com/challenges/nested-list/problem
Nested List
'''
if __name__ == '__main__':
students = []
for _ in range(int(input())):
name = input()
score = float(input())
students.append([name, score])
# sort by grade
students.sort(key=lambda a: a[1])
... |
30a508c37aae8b67fd080260583392ef589a199a | 22scofield/entego-caws-bulls-game | /bulls-cows.py | 3,062 | 3.5625 | 4 | import random
#Hlavní funkce, která řídí běh hry
def main():
start_game()
gen_secret_num()
#Počet pokusů uživatele
max_user_attempts = 10
play_game(sec_num, max_user_attempts)
#Dialog s uživatelem o tom, zda chce začít hru, nebo ne
def start_game():
while True:
user_start = input("You ... |
c8efb49aaa1ff878936ae7467dde77c5dd188597 | djsaunde/EstimatingAndExplainingTwitterEngagement | /code/get_data.py | 3,135 | 3.859375 | 4 | '''
This script will scrape data from Twitter, using the python-twitter Twitter API
wrapper. Default behavior (no parameters) will be to scrape some number of
tweets from specific Twitter handles. With parameters specified (in the form
of strings), this script will get a certain number of tweets from specified Twitter... |
011a96e100fcd403ed11aa5c8f7c84cebd96992f | evelynywyu/evelynywyu.si507.w18 | /Lecture 10 /simplified_twitter.py | 982 | 3.9375 | 4 | # Lecture 10 - Feb 6
# simplified_twitter.py
from requests_oauthlib import OAuth1
import json
import sys
import requests
import secret_key
username = sys.argv[1]
num_tweets = sys.argv[2]
consumer_key = secret_key.CONSUMER_KEY
consumer_secret = secret_key.CONSUMER_SECRET
access_token = secret_key.ACCESS_KEY
access_s... |
ff877d7b132c80d576f8e9a57d392bff524b98a7 | neema80/python | /try_except.py | 1,143 | 4.5 | 4 | # we use try and except method to change the error messages that system
# generates and make our own error messageg
for i in range(5):
try:
print(i/2)
except ZeroDivisionError as e: # e is a variable for usage
# however it is not mandatory but is good practice for better code maintaining
... |
5837481fba1375c179f9e84291af132759c4d376 | kumaharaj/Python-Code | /Python Programmingg/variable1.py | 558 | 3.859375 | 4 | c = 20 #global variable C
def func(): #defining function func
c = 10 #Redefining variable C, this is called local variable because it is present under a function
print(c) #printing local value of variable C
func() #calling function which is defined
print(c) #printing the global v... |
460a98bcc727be4f8d124a1245249ceb80da5f47 | prasadshirvandkar/Algorithms | /Python/pascals_triangle.py | 2,125 | 3.640625 | 4 | # pascals_triangle.py
from misc_functions import Stopwatch
def Binom_coeff_tab(n,k): #tab for tabulation
# print "Binomial coefficients by tabulation"
n=n+1 #just for allowing us to normalize the inputs
pas=[]
for i in range (0,n):
pas.append([0 for x in range(0,n)])
pas[0][0]=1
for i in range(1,n):
for j ... |
ad3ec86bd15005fc2eef200b0bb6e31bc40cef34 | Nisar-1234/Data-structures-and-algorithms-1 | /LinkedList/Circular LL/Questions/Split a Circular Linked List into two halves.py | 4,922 | 4.0625 | 4 | # NOTE: Logic to split a circular linked list:
# 1) we have to find the middle and the last node
# 2) then we have to store the next pointer of this middle and last node
# 3) then we have to change these ponters according to split the circular LinkedList
class Node():
def __init__... |
ec9225b5760f8b6030b8cfb0231fe12456c4cd47 | XYPB/HOMEWORK-2019 | /python/Learning_Test.py | 495 | 3.5 | 4 |
# coding: utf-8
# In[6]:
a = [1, 2, 3, 4, 5]
a_iter = iter(a)
for i in range(5):
print(next(a_iter))
# In[7]:
try:
print(next(a_iter))
except StopIteration:
print('Iterator out of range')
# In[17]:
def xjbfunc(a):
while 1 == 1:
if (a > 10):
return 0
a += 1
... |
6134300f855d49a449402a2d64b369f29adda107 | kellyeschumann/comp110-21ss1-workspace | /exercises/ex10/basketball.py | 1,186 | 4.0625 | 4 | """A class to model a basketball game."""
__author__ = "730314660"
# TODO 1: Define the BBallGame class, and its logic, here.
class BBallGame:
"""Represents a basketball game."""
biscuts: bool
points: int = 0
winning_team: str
losing_team: str
def __init__(self, points: int, winning_team: s... |
b57476a20e1c14a6d0e04b7be5b4e08e5605faf8 | iseliner/DuoLine | /main.py | 1,175 | 3.65625 | 4 | """
The plan is to make a web game supporting multi-play, where each player puts down two lines (can expand
to more choices for amount of lines) before switching to the next player. Each player have their own
color, and together you can make pieces of art.
"""
from tkinter import *
canvas_width = 600
canvas_height = ... |
f0190f294346636629174c13786fdd1747a96df1 | tanarj/event_scraper | /web_scrapers/EventScraper.py | 1,915 | 3.625 | 4 | """Event Scraper class that uses requests, as well as BeautifulSoup4 to scrape event information from websites
of interest
Copyright (c) 2017 Arjun Tanguturi (tanarj)
License: BSD 3
"""
import requests
from bs4 import BeautifulSoup
from event_ontologies.Event import PlannedEvent
web_elems = {
"United Center"... |
a4305968dcbb488312ccef3c9a320c49ac41cefb | sahil101/Py---Files | /try/except.py | 350 | 3.96875 | 4 |
def largest():
print("Maximum is {0}".format(max(list1)))
print("Minimum is {0}".format(min(list1)))
print(list1)
x = 0
x1 = 0
list1 = []
while True:
x = input("enter a number")
if x == "done":
largest()
break
try:
x1 = int(x)
list1.append(x1)
except:
... |
9866925c942268f2b231b36c4a2ffbe0755d805e | rpparas/LeetCode-Programming-Problems | /Trees/SymmetricTree.py | 1,530 | 4.1875 | 4 | # Problem Statement: https://leetcode.com/problems/symmetric-tree/
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
if not root:
... |
2402c123e1cff72c2f105b4dbf22da3d9f42533d | oscar6echo/py-multiprocessing | /my_package/my_class.py | 663 | 3.6875 | 4 | from time import sleep
from timeit import default_timer as timer
class MyClass:
def __init__(self, name, start, end, time):
self.steps = [e for e in range(start, end)]
self.time = time
self.name = name
self.res = 'toto'
def run(self, queue):
t0 = timer()
c = 1... |
bc057c0c826c618d3c257de3a43e0c708d7d228d | anton-dovnar/LeetCode | /Stack/1021.py | 909 | 3.875 | 4 | """
Remove Outermost Parentheses
Runtime: 36 ms, faster than 80.25% of Python3 online submissions
for Remove Outermost Parentheses.
Memory Usage: 14.1 MB, less than 94.74% of Python3 online submissions
for Remove Outermost Parentheses.
"""
class Solution:
def removeOuterParentheses(self, s: str) -> str:
... |
f9a7aa48754a36eeea744252bb2dc80df495c187 | twall5/cardiff_python_course | /readfilefruit.py | 319 | 3.5625 | 4 | import random
fruitlist = []
file = open('fruit','r')
for line in file:
line = line[:-1]
print(line)
fruitlist.append(line)
file.close()
print(fruitlist)
fruits = ' '.join(fruitlist)
print(fruits)
fruitlist = fruits.split(' ')
print(fruitlist)
word = fruitlist[random.randint(0,8)]
print(word) |
7ee24af6ff24bdb1eb3c7440b684018744780854 | daniiarkhodzhaev-at/lab3 | /4.py | 1,402 | 3.8125 | 4 | #!/usr/bin/python3
import turtle
import random
dt = 0.01
vx = 10
vy = 0
ax = 0
ay = -10
# This is not exactly energy, it's divided by mass (because it's proportional to it)
def get_energy() -> float:
return (turtle.dot_x ** 2 + turtle.dot_y ** 2) / 2 - turtle.pos()[1] * ay
# Just double integration
def dull_sim... |
324854a853a24054d18be5f31e6e1b854b457e86 | annieneedscoffee/python-ninjas | /app.py | 1,424 | 3.59375 | 4 | import random
class Human:
health = 30
name = ""
def __init__(self, name):
self.name = name
def eat(self):
self.health+=5
myHuman = Human("Hassan")
myHuman.eat()
print(myHuman.health)
class Ninja(Human):
health = 10
def __init__(self, name):
Human.__init__(self, name)
def me... |
fe82cfc9598932a9d4ac3681b3f0cbdae75ce31a | MakrisHuang/LeetCode | /python/253_meeting_rooms_II.py | 774 | 3.515625 | 4 | class Solution:
def minMeetingRooms(self, intervals: List[List[int]]) -> int:
if not intervals: return 0
free_rooms = []
# since we want to check next available room
# sort the intervals by start time
intervals.sort(key=lambda x: x[0])
# add the first meeting. We h... |
782154a7ae9fd568dcc2dccdbe0c106380df5bf0 | Vchenhailong/my-notes-on-python | /basic_rules/chapter_1/file_demo.py | 828 | 3.8125 | 4 | #! /usr/bin/python
# coding:utf-8
import webbrowser
from fileinput import close
def file_reader():
try:
for line in open("/Users/hailongchen/Desktop/测试数据"):
print(line, end=' ')
# 捕获异常
except (FileExistsError, BaseException):
# 抛出异常
raise Exception
# 无论如何,最终将之关闭(这里不... |
268b4c3d50286a98a9afeefd815fe78710d66e4b | RichieSong/algorithm | /算法/动态规划/三角形最小路径和.py | 1,336 | 3.625 | 4 | # coding:utf-8
'''
给定一个三角形,找出自顶向下的最小路径和。每一步只能移动到下一行中相邻的结点上。
例如,给定三角形:
[
[2],
[3,4],
[6,5,7],
[4,1,8,3]
]
自顶向下的最小路径和为 11(即,2 + 3 + 5 + 1 = 11)。
说明:
如果你可以只使用 O(n) 的额外空间(n 为三角形的总行数)来解决这个问题,那么你的算法会很加分。
'''
class Solution:
def minimumTotal(self, triangle):
"""
:type triangle: List[Lis... |
97c1ddb97521f9d814857bceb5209f71dcf11ebf | dvelasquev/ST0245-008 | /TallerRecursion/InvertirString.py | 294 | 4 | 4 | def reverse_palabra(Palabra,num):
if num>0:
print(Palabra[num],end='')
reverse_palabra(Palabra,num-1)
elif num == 0:
print (Palabra[0])
str = input ("Ingrese una cadena de caracteres: ")
print("La cadena invertida es: ")
reverse_palabra(str,len(str)-1) |
57e7363796c74c473b57605fe9ffae991fab7f5c | bl-kt/y1-cw-projects | /py-cw/2005906.py | 3,224 | 3.90625 | 4 | from graphics import *
def getInputs():
#windowsize
windowSize = int(input("Enter your window size."))
while not (windowSize != 5 or windowSize != 7):
print("This is not a valid window size. The valid sizes are: 5 and 7.")
windowSize = int(input("Enter your window size."))
#colours
va... |
52466128ba526d51a0a66e689a56c1e849109f9e | seanreed1111/TTP-Python-Assessment | /Python-Assessment-Final-Doc-Solutions.py | 5,956 | 4.25 | 4 |
# coding: utf-8
# In[ ]:
''' #1
Write a function called 'addBetween'.
Given 2 integers, "addBetween" returns the sum
of all numbers between the two given integers,
beginning at num1, and excluding num2.
If num2 is not greater than num1, the function should return 0.
output = addBetween(3, 7)
print(output) # --... |
17d4742c8fd6ea195902ae8e057ac54a039ca8e2 | Jason-Yuan/Interview-Code | /CTCI/Python/Chapter9-11.py | 2,647 | 3.703125 | 4 | ##############################################################################################################################
# Ideas: Recursion with memorization
# Dynamic Programing
# Use cache = {} as a hash map
# Time Complexity: O(n!)
# Space Complexity: O(n)
########################################... |
e639fc901b3d4ba9b0c6a4c8c9c835265ee41c0d | Arjitg450/Python-Programs | /dfgdfg.py | 244 | 3.53125 | 4 | import random
s = "abcdefghijklmnopqrstuvwxyz01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()?"
lengthinput=int(input("Enter the length of password you want : "))
for i in range(lengthinput):
p="".join(random.choices(s))
print(p,end="")
|
e0919bc4e78e0e4a114066e19a10e4602d4ad0b4 | HarnishSavsani/Python-programming | /Web scraping project.py | 1,571 | 3.671875 | 4 | from bs4 import BeautifulSoup
import requests
url="https://getpython.wordpress.com/"
source=requests.get(url)
soup=BeautifulSoup(source.text,'html')
title=soup.find('title') # place your html tagg in parentheses that you want to find from html.
print("this is with html tags :",title)
qwery=soup.find('h1') # here i... |
2ee153bc57aad6eebe3dcd806439402b1e2b175e | xipengwang/Deep-RL-Bootcamp | /lab1/p1.py | 6,048 | 3.515625 | 4 | #!/usr/bin/env python3
from misc import FrozenLakeEnv, make_grader
env = FrozenLakeEnv()
print(env.__doc__)
# Some basic imports and setup
import numpy as np, numpy.random as nr, gym
import matplotlib.pyplot as plt
np.set_printoptions(precision=3)
# Seed RNGs so you get the same printouts as me
env.seed(0); from gy... |
87596a00e30239b27e7bd3ab7cfe38b72d597da9 | BunniwuvsPoni/Tools | /Python/Import CSV/Import CSV with default CSV module.py | 819 | 3.90625 | 4 | # This function imports a .CSV file and prints the content to the console using the CSV module
import csv
# Import, process, and print .CSV file
# Setting encoding to UTF-8 due to error: (UnicodeDecodeError: 'charmap' codec can't decode byte 0x90 in position XXX: character maps to <undefined>)
with open("C:\Devel... |
9929866836660b64551dffbf4b58debda22efd37 | im965/final_project | /portfolioFactory/utils/getFileLocation.py | 483 | 4.15625 | 4 | """
This function creates a pop-up that asks the user to select a file for input
Author: Peter Li
"""
import Tkinter,tkFileDialog
def getFileLocation(msg):
''' This function opens a GUI that takes in user selection files
Input:
- msg (str): Message displayed on the top of the window
... |
9f42f6ef9ecfa9fee0111c7b90d969aeeb1f8563 | sirdesmond09/univel | /lyricsfinder.py | 1,199 | 4.09375 | 4 | # lyrics = open('lyrics.txt', 'r', errors='ignore')
# user_input = input('Please enter word \n Seperate by comma for multiple words \n > ')
# could_not_find_word = True
# for word in lyrics.readlines():
# if user_input in word:
# lower_case_word = word.lower()
# lower_case_word = lower_case_word.r... |
c4dbcf39b5b727a669b081e03769ebfbc2bc8465 | higor-gomes93/curso_programacao_python_udemy | /Sessão 4 - Exercícios/ex7.py | 389 | 3.984375 | 4 | '''
Leia uma temperatura em graus Fahrenheit e apresente-a convertida em graus Celsius. A fórmula de conversão é:
C = 5*(F-32.0)/9.0, sendo C a temperatura em Celsius e F a temperatura em Fahrenheit.
'''
temp_fahrenheit = float(input("Insira a temperatura em graus Fahrenheit: "))
temp_celsius = 5*(temp_fahrenheit - 32... |
ae04186843d1ad49ca8155ce37a429e0632d214a | yar-kik/Epam-homework | /task4/task_4_ex_11.py | 705 | 4.34375 | 4 | """
Write a function `fibonacci_loop(seq: list)`, which accepts a list of values and
prints out values in one line on these conditions:
- floating point numbers should be ignored
- string values should stop the iteration
- loop control statements should be used
Example:
>>> fibonacci_loop([0, 1, 1.1, 1, 2, 99.9, 3,... |
b61e9faba1b43d0622c11632d5c779d57781df81 | MoisesSDelmoro/Python-basico-ao-avancado | /if_else_elif.py | 206 | 4.03125 | 4 | """
idade = 18
if idade < 18:
print("Menor de idade")
elif idade == 18:
print("Faixa atual")
else:
print("Maior de idade")
"""
ativo = 10
if ativo:
print("true")
else:
print("false")
|
fc881b88f788f9eca8ae3e6c97bf84e7fd576e15 | QiangBB/python_learning | /字典.py | 320 | 3.84375 | 4 | a_list=[1,2,3,4,5,6]
# 字典,类似于map,内部无顺序,很灵活,可以在字典里再套字典
d={'apple':1,'pear':2,'orange':3,'new':{3:0,2:1}} #前一个是key,后一个是所对应内容
d2={1:'a','c':'b'}
print(d['apple'])
del d['pear'] #删除一个元素
d['b']=20 # 新增元素
print(d['new'][2])
|
2076311ef6cbe800518414703c724d33d4fbf6a5 | IronmanJay/Python_Project | /NumericalAnalysis/lagrange.py | 1,071 | 3.5625 | 4 | import matplotlib.pyplot as plt
import math
# 给出一组数据进行lagrange插值,同时将结果用plot展现出来
def lagrange(x_,y,a):
"""
获取拉格朗日插值
:param x_: x的列表值
:param y: y的列表值
:param a: 需要插值的数
:return: 返回插值结果
"""
ans = 0.0
for i in range(len(y)):
t_ = y[i]
for j in range(len(y)):
if... |
eb8b37378c85c37e04c14897d1bcb3344dd5a5a7 | Surbhi-Golwalkar/Python-programming | /Statements/p8.py | 172 | 4.21875 | 4 | names = ["surbhi","shruti","aaradhya"]
name = input("enter the name to check\n")
if name in names:
print("your name exist in the list")
else:
print("not in list")
|
accb8c9d39df2cc154dad19d5ea3e9ce46c25e83 | OhRaeKyu/Python_Self-Study_Basic | /제 1장/2_if.py | 142 | 3.859375 | 4 | x = input("정수를 입력하시오 : ")
x = int(x)
if x < 2:
print("Low")
elif x>=2 & x<20:
print("Mid")
else :
print("High") |
ed3e1160a637f82b993fa51e9a876746c11ee1f0 | RapunzeI/Python | /Chapter_5/42.py | 391 | 3.59375 | 4 | def primeFac(n):
primeList=[]
for i in range(2, n+1):
bData=True #소수임
for k in range(2, i):
if i%k==0:
bData=False #소수가 아님
break
if bData:
while(n%i==0):
primeList.append(i)
n=n/i
retu... |
088b0b4d9bef01616fe0674f263608ae07056211 | erishan6/ProgCL | /lab4/list_examples.py | 5,010 | 4.28125 | 4 | # -*- coding: utf-8 -*-
"""
This program consists of few simple functions which demonstrate operations on lists.
[!] marks places which need taking care of (either changing or adding new code).
A correct result of this program is in file 'list_examples_out.txt'
"""
def is_even(n): # done with changes
"""
... |
36c29eb034a1d0fc5a0e2d0457841bf4a21f7daa | kikijtl/coding | /Candice_coding/Leetcode/Min_Stack.py | 1,215 | 4.0625 | 4 | class MinStack:
def __init__(self):
self.st1 = []
'''st1 is the original stack'''
self.st2 = []
'''st2 is used to store the minimum value'''
# @param x, an integer
# @return an integer
def push(self, x):
self.st1.append(x)
if not self.st2 or x <=... |
b572b49a28e8c499ff041799b2156443fc45dc36 | KorsakovPV/yandex_contest | /13_Yandex_Contest 1/A/A-Алексей_Зверев.py | 525 | 3.609375 | 4 | n = int(input('Введите количество уроков: '))
lessons_time = []
for i in range(n):
s = input()
lessons_time.append([float(s.split()[0]), float(s.split()[1]), s])
sorted_lessons_time = sorted(lessons_time, key=lambda x: (x[1], x[0]))
timetable = [sorted_lessons_time[0]]
end_time = timetable[0][1]
for time in sor... |
148cac056de92408152f6b7a02168d0301fdb848 | karoberts/adventofcode2015 | /01-2.py | 208 | 3.515625 | 4 |
with open('01.txt' ) as file:
line = file.readline().strip()
floor = 0
for i, c in enumerate(line):
floor += 1 if c == '(' else -1
if floor == -1:
print('basement', i + 1)
print(floor)
|
3bf40db92f4fec6314caf17fde81b959e9bb8d51 | apu031/PyGameCollection | /Introduction to Python (Coursera)/Part1 (Basic)/Week4/stopwatch.py | 3,397 | 3.78125 | 4 | # template for "Stopwatch: The Game"
# CodeSkulptor URL: http://www.codeskulptor.org/#user47_L62YisLKKPm2dXe.py
__author__ = "Apu Islam"
__copyright__ = "Copyright (c) 2016 Apu Islam"
__credits__ = ["Apu Islam"]
__license__ = "MIT"
__version__ = "1.0"
__maintainer__ = "Apu Islam"
# Importing Modules
import simplegui... |
e55a10bff309acb93c9b3c00a5253d180b91708f | Nayan356/Python_DataStructures-Functions | /DataStructures_2/pgm11.py | 468 | 4.15625 | 4 | # Write a program to find out the occurrence of a specific word
# from an alphanumeric statement. Example: 12abcbacbaba344ab
# Output: a=5 b=5 c=2 make sure you should avoid the numbers in you logic
def word_count(str):
counts = dict()
words = str.split()
for word in words:
if word in counts:
... |
57e5c5af9c1a79dc90319011ffec20591bb14dc3 | snu-python/pythonbook | /exercise/ex5_2.py | 1,049 | 3.6875 | 4 | #!/usr/bin/env python
"""This file is provided for educational purpose and distributed for class use.
Copyright (c) by Jinsoo Park, Seoul National University. All rights reserved.
File name.....: ex5_2.py
Description...: Sample solution for exercise 5-2.
This program demonstrates how to use single quot... |
3bd52481bb6202c3f2a36d8f128eda6d3ba9ca99 | lgigek/alura | /python3/games/hangman.py | 1,637 | 3.890625 | 4 | import random
def play():
print_init_message()
secret_word = create_secret_word()
guessed_right_letters = create_guessed_right_letters(secret_word)
print(guessed_right_letters)
is_hanged = False
is_correct = False
current_errors = 0
max_errors = 6
while not is_hanged and not is_... |
c5323c0c73f237fd6dfd4feca2689a5f150fb924 | MCBoarder289/PythonArcadeGames | /Labs/Chapter 6 - Lab Pygame Exercise.py | 2,230 | 4.21875 | 4 | """
Pygame base template for opening a window
Sample Python/Pygame Programs
Simpson College Computer Science
http://programarcadegames.com/
http://simpson.edu/computer-science/
Explanation video: http://youtu.be/vRB_983kUMc
"""
import pygame
# Define some colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN... |
a261671903176fd214025d8613be32ac68782dd4 | alee2021/demo | /main.py | 2,271 | 3.71875 | 4 | # file created by Allan Lee
# thanks Chris Bradfield from Kids Can Code
'''
Submit a .py file with a project proposal in the comments including:
What's your project? The video game project walkthrough
What is your first major milestone? Making the pokemon rock, paper, scissors game
What do you not know that you will n... |
4ac8aafa29a1ba5ff3ab6d76e1e54ffaabdd0154 | Lokesh824/LeetCode | /Reverse_LinkedList.py | 987 | 4.09375 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
"""
... |
ec790e6c0a152dc1e265eca02a880013bf3c164a | anag33/SMU_Data_Science_Projects | /03-Python/Submissions/PyPoll/Resources/main.py | 2,574 | 3.5625 | 4 | # Modules
import csv
# Set path for file
csvpath = r"Submissions\PyPoll\Resources\election_data.csv"
# Counter for the votes
totalVotes = 0
# Declare variables
votesKhan = 0
votesCorrey = 0
votesLi = 0
votesOtooley = 0
# Open the CSV
with open(csvpath) as csvfile:
csvreader = csv.reader(csvfile, delimiter=","... |
e60758971c4beae7dec4268f08efb43080edf612 | ymtcham/Python_tutorial | /49_in_statements.py | 496 | 3.859375 | 4 | q1 = input("Hi there, what's your name? \n")
print('-' * 100)
q2 = input("How are you today, {}?\n".format(q1))
print('-' * 100)
if ('well' or 'good' or 'ok' or 'fine' or 'alright' or 'cool' or 'great') and not 'not' in q2:
print('Glad to hear that, {}'.format(q1))
else:
print("Sorry, to hear that. I wish ther... |
0dddc7b9147efdffa494aed27337e4c39d9295d7 | ZhangYajun12138/unittest | /work_hard/ex16.py | 1,022 | 3.546875 | 4 | #coding:utf-8
'''
close -----关闭文件
read -----读取文件内容,返回一个值
readline -----读取文本文件中的一行
truncate -----清空文件
write(stuff) -----将stuff写入文件
'''
from sys import argv
(script,filename) = argv
print("We are going to erase %r." %filename)
print("If you don't want that, hit CTRL-C.")
print("IF you do want that, hit RETURN.")
input("?... |
4c25ecafd948b5923467710cbacf3c5ddbe1face | Sodiq-123/Python-In-GIS | /week4/codes/list-code-3.py | 1,180 | 4.5 | 4 | # list methods 2
# we will be going over some uses of lists
# let's first create 2 lists
my_first_list = [1, 2, 3, 4, 5]
my_second_list = [6, 7, 8, 9, 10]
# reversing a list
my_first_list.reverse()
print(my_first_list)
# sorting a list
my_second_list.sort()
print(my_second_list)
# adding 2 lists
my_third_list = my_... |
98880f390646d867a86fbc678118a26eaf8bd79e | Karpo22/Project-Euler | /Problem 7.py | 766 | 3.796875 | 4 | import random
controlInt = 1
x = 0
## Fermat primality test
## NOTE: THIS IS ONLY PRACTICAL WITH SMALLER NUMBERS
## IF YOU ARE TESTING LARGER NUMBERS, INCREASE
## THE RANGE IN "TIME" OR ELSE IT MAY RETURN
## FALSE POSITIVES/NEGATIVES
def FermatPrimalityTest(number):
if (number > 1)... |
3bbdfaed7fee5e8f1f69507413931604665cd61c | gagaspbahar/prak-pengkom-20 | /P03_16520289/P03_16520289_03.py | 1,537 | 3.515625 | 4 | # NIM/Nama : 16520289/Gagas Praharsa Bahar
# Tanggal : 18 November 2020
# Deskripsi: Problem 3 - Kemunculan 'tuan' pada Subsequence
# # Kamus
# int n = panjang string
# string s = string yang ingin dicek
# int muncul = jumlah kemunculan
# Inisialisasi nilai panjang, string, dan jumlah kemunculan
n = int(input("Masuk... |
9d87278f11d59b9173665234f1fbd0d922552f05 | bockman83/test2 | /ex5.py | 478 | 3.59375 | 4 | my_name = 'Zed A. Shaw'
my_age = 35 # not a lie
my_height = 74 # inches
my_weight = 180 #pounds
print "Let's talk about %s" % my_name
print "He's %d inches tall." % my_height
print "I can add %d and %d to get the number %d" % (
my_age, my_height, my_age + my_height )
my_kilo_weight = my_weight / 2.2
my_metric_heigh... |
6db0ffdcf46f9074193dde6363125d2fb839375d | dejikadri/tictactoe | /app_helper.py | 1,785 | 3.984375 | 4 | import re
def validate_board(board):
'''
This function checks that a valid board is sent as input
'''
if len(board) == 9 and valid_characters(board):
return True
def valid_characters(strg):
'''
This function checks that the board contains only valid characters
'''
search = re.c... |
34400ef275b2a16fa2fbd5b72f6e16c9baf3c407 | Lavanyamca22/Implementation_Programs | /Total_Rated_Members_Byboth_Using_Set_Intersection.py | 203 | 3.578125 | 4 | def main(a,b):
# Write code here
print(len(a.intersection(b)))
A = int(input())
List_A = set(map(int,input().split()))
B = int(input())
List_B = set(map(int,input().split()))
main(List_A,List_B)
|
a2139254e89531e6dcae81ed5def6e4e3d85983c | dzerenyuk/automation | /homework_1/task_05.py | 117 | 3.96875 | 4 | # fifth task
string = input('Enter your string: ')
number = int(input('Enter your number: '))
print(string * number)
|
c1bdc19ca244d4fc7fea17e5d8a7ada8b8e77f6c | pratik-walawalkar/reformat_images | /reformat_images.py | 776 | 3.703125 | 4 | #!/usr/bin/env python3
from PIL import Image
import os
import sys
source_folder = "/home/student-04-fc2745a2c9db/images/"
destination_folder = "/opt/icons/"
def reformat():
for item in os.listdir(source_folder):
if os.path.isfile(source_folder+item):
im = Image.open(sourc... |
757c6fe3153fdf937d017850678d0cecbed7ce2b | tum0xa/cli-dice-poker | /dice-poker.py | 8,107 | 3.703125 | 4 | import random
import os
NUM_OF_FACES = 6
NUM_OF_DICES = 5
NOTHING = 0
PAIR = 2
SET = 3
CARE = 4
POKER = 5
STRAIGHT = 100
FULL_HOUSE = 23
sym_dices = { 1: '⚀',
2: '⚁',
3: '⚂',
4: '⚃',
5: '⚄',
6: '⚅',
}
class Dice:
"""
Class... |
e5788223234273b762fec0f60ac3d9d94799786c | abdelrahmanIEl-Batal/ML-Assignments | /Linear-and-Logistic-Regression/Logistic_Regression.py | 2,008 | 3.734375 | 4 | import pandas
import math
import numpy as np
import matplotlib.pyplot as plt
def sigmoid(z):
return 1 / (1 + np.exp(-z))
def computeCost(X, y, theta):
m = X.shape[0]
z = np.dot(X, theta)
firstHalf = y * np.log(sigmoid(z)) # predict 1
secondHalf = (1 - y) * np.log(1 - sigmoid(z)) # predict 0
... |
c650ea9035d4d62aa80fcdaf050cb1055e132635 | czalucky/PythonPlotsPractice | /OOMethodPlot.py | 567 | 3.609375 | 4 | import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 5, 11)
y = x ** 2
# Creates blank canvas
fig = plt.figure()
axes1 = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # main axes
axes2 = fig.add_axes([0.2, 0.5, 0.4, 0.3]) # inset axes
# Larger Figure Axes 1
axes1.plot(x, y, 'b')
axes1.set_xlabel('X label')
ax... |
95dd1bca0d880e020a25ab03a8a5ba4016fd5070 | refeed/StrukturDataA | /meet9_22_April_2021/F_BSTButReversed.py | 3,212 | 3.578125 | 4 | '''
Cermin Tree
Batas Run-time: 1 detik / test-case
Batas Memori: 32 MB
DESKRIPSI SOAL
Membentuk Cermin Tree dari N data (N<=0), tp tidak boleh ada angka yang sama.
Cermin Tree adalah efek Tree yang dicerminkan. Kita tahu efek dari suatu cermin
adalah membalik yang kanan menjadi kiri dan sebaliknya. Sehingga Cermin... |
6bb8c852187395a760bc61cd92287a6e4f5c7db1 | Slavik0041/BelHard_education | /bh_7_tasks-master/easy/inheritance_polimorphism/duck_typing.py | 754 | 4.28125 | 4 | """
Создать 3 класса:
Cat, Duck, Cow
в каждом классе определить метод says()
Cat.says() - кошка говорит мяу
Duck.says() - утка говорит кря
Cow.says() - корова говорит муу
Написать функцию animal_says(), которая принимает объект и вызывает метод says
"""
class Cat:
def says(self):
print(f'Кошка говори... |
8b678ffb3a2b8546d3561b22b6507f746fa3da7c | JohnnyAIO/Python | /Centigrados.py | 515 | 3.71875 | 4 | c = int(input("Ingrese la temperatura en centigrados"))
f = (9*c/5) + 32
print("Total de Farenheit: %d " % f)
auto = int(input("Ingrese la cantidad de km recorridos "))
dias = int(input("Ingrese la cantidad de dias obtenidos "))
#6obs.f por dia alquilado el auto
#0,15bs.f por km alquilado del auto
auto_t = aut... |
6ddeeca7091668a9a9d81b9e43531f5666401c82 | yehongyu/acode | /2019/dfs/cheapest_flights_within_k_stops_1029.py | 1,001 | 3.546875 | 4 | import sys
class Solution:
"""
@param n: a integer
@param flights: a 2D array
@param src: a integer
@param dst: a integer
@param K: a integer
@return: return a integer
"""
def findCheapestPrice(self, n, flights, src, dst, K):
# write your code here
graph = {}
... |
000564a9727c72076199730fd1ba0fb2386b3a7c | Eelin-xyl/Python | /Python草稿本/遍历字典.py | 437 | 4.125 | 4 | a = {'a': '1', 'b': '2', 'c': '3'}
for key in a:
print(key+':'+a[key])
# a:1
# b:2
# c:3
for key in a.keys():
print(key+':'+a[key])
# a:1
# b:2
# c:3
for value in a.values():
print(value)
# 1
# 2
# 3
for kv in a.items():
print(kv)
# ('a', '1')
# ('b', '2')
# ('c', '3')
for key, value in a.items():
... |
9a1c3adcf5f8a16cd67b8b6524f12b5375ac0bb0 | kjsu0209/CodingTest | /programmers/p42746.py | 1,026 | 3.640625 | 4 | def solution(numbers):
answer = ''
string = ''
#첫 자리 숫자가 제일 큰 것부터 정렬
numbers = quicksort(numbers)
for n in numbers:
answer += str(n)
if answer[0] == "0":
answer = "0"
return answer
def quicksort(x):
if len(x) <= 1:
return x
pivot = x[len(x) // 2]
pi... |
f77220aa8062ac7d4f22383b5249c621300cf339 | skshihab069/Data-Structure | /problem solving/combine lists using zip.py | 259 | 3.546875 | 4 | # with the help of zip function you can combine two lists
movies = ["Hacksaw Ridge", "Forest gump", "The butterfly effect", "the conjuring"]
ratings = [7, 9, 10, 8]
new_list = []
for items in zip(movies, ratings):
new_list.append(items)
print(new_list)
|
934506e384c05abb838933cc3ed4569803c0082c | cpe202spring2019/lab1-jpcastil | /location_tests.py | 790 | 3.703125 | 4 | import unittest
from location import *
class TestLab1(unittest.TestCase):
def test_repr(self):
"""Tests for: Repr returns correct information in format"""
loc = Location("SLO", 35.3, -120.7)
self.assertEqual(repr(loc),"Location('SLO', 35.3, -120.7)")
def test_eq(self):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.