blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
f058c95b2b61b8d7a79fbd9e5ed0050d8c1b46d9 | czs108/LeetCode-Solutions | /Easy/844. Backspace String Compare/solution (1).py | 600 | 3.734375 | 4 | # 844. Backspace String Compare
# Runtime: 24 ms, faster than 96.27% of Python3 online submissions for Backspace String Compare.
# Memory Usage: 14.3 MB, less than 51.80% of Python3 online submissions for Backspace String Compare.
class Solution:
# Build String
def backspaceCompare(self, s: str, t: str) -> ... |
cc7209708963edd56e68b3cce1b4239613cdbd16 | seddon-software/python3 | /Python3/src/06 Regular Expressions/01_split.py | 322 | 3.953125 | 4 | #######################################################
#
# split
#
#######################################################
import re
x = "hello-to-you".split("-")
print(x)
pattern = re.compile(r"[\s^;]+")
text = " aaa ; bbb ;ccc ; ^ ddd ; eee "
mylist = pattern.split(text.strip())
print(mylist)... |
feb9e0f1d712cfba94fc10978e8aebd02c938683 | marththex/Python | /MarcusChong_4/complement.py | 1,456 | 4.375 | 4 | #complement.py
#Write a module, complement.py, with a function, complement, that returns the
#complement of a DNA string. Also provide a function, revComplement that takes a
#DNA sequence as string input and returns the reverse complement of the sequence as a
#string. Recall that the valid alphabet is {A,C,T,G} and tha... |
8c840da5a2df10a659f6126271bc87fa99976b6f | PeterMurphy98/comp_sci | /sem_1/programming_1/prac9/p17p2.py | 1,065 | 4.09375 | 4 | # Define a function that returns the list of common divisors of x and y.
def divisor(x,y):
"""Finds the common divisors of x and y."""
# Check if x or y divide each other.
if max(x,y) % min(x,y) != 0:
# If not, initialise the list of common divisors with 1.
divisors = (1,)
# Check if... |
4671e746a797db39107f924a8700d17acb8f1a59 | dmitry-dereshev/Guess-the-Book | /06_mic_trees_feature_selection.py | 4,552 | 3.515625 | 4 | # Part of Guess the Book project by Dmitry Dereshev. MIT Licence 2019.
# https://github.com/dmitry-dereshev/guess-the-book-public
# Takes in the split sets from 05_scaling_splitting_sets.py, identifies top
# features based on mutual info classifier and classification trees, and saves
# the new datasets with those... |
0b1103f09549242424bc77ab04d72ac51c30de35 | misohu/python_basics_examples | /08_loops.py | 1,013 | 3.984375 | 4 | # Loops
numbers = [1, 2, 3, 4, 5, 10]
letters = ["M", "i", "c", "h", "a", "l"]
# The for loop
for number in numbers:
print(number)
# Lazy to write the array
range(4)
list(range(4))
list(range(0,4))
list(range(1,4))
list(range(0, 10, 2))
list(range(10, 1, -2))
for number in range(0, 10, 2):
print(number)
#... |
08f825a40acf54f0b52692be4941d38fcfe9ea5d | guhaigg/python | /month01/day02/exercise08.py | 261 | 3.59375 | 4 | """
练习2:古代的秤,一斤十六两。
在终端中获取两,计算几斤零几两。
"""
total_liang = int(input("请输入总两数:"))
jin = total_liang // 16
liang = total_liang % 16
print("结果为:"+str(jin)+"斤"+str(liang)+"两") |
7b661906cfa8d0237d53edcad3588dc7d5c8d383 | lavi09/Linked-Lists | /rotatelinkedlistbyknodes.py | 1,265 | 3.890625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jun 7 10:44:20 2019
@author: Lavi
"""
class Node:
def __init__(self,data):
self.data=data
self.next=None
class LinkedList:
def __init__(self):
self.head=None
def push(self,new_data):
new_node=Node(new_data... |
48902bb0721a93d80407711c0676f60c09c1fdc2 | fatoukine/cours1 | /seance3.py | 1,697 | 3.875 | 4 | class animal:
def __init__(self, type, age, sexe):
self.type = type
self.age = age
self.sexe = sexe
def __str__(self):
return "Cet animal est un(e) " + self.type + " son age " + str(self.age) + " son sexe " + self.sexe
class farm:
def __init__(self, nom):
... |
1726e009ed88f2aa8abec3006227afecdf924ae8 | ConnorStout/ProjectEuler | /Problem_14/Problem14.py | 402 | 3.796875 | 4 | def recurse(n, deep):
if (n == 1):
return (1)
if (n % 2 == 0):
return 1 + recurse(n / 2, deep)
else:
return 1 + recurse(((3 * n) + 1), deep)
longest = 10
longestNum = 13
curr = 13
while curr<890000:
currRun = recurse(curr,2)
if(longest<currRun):
longest = currR... |
c1d23b401a7b69e9f816791f45e32542da78af60 | Jamin2018/Python_improve_training | /第4章:字符串处理/4-6如何去掉字符串中不需要的字符.py | 982 | 3.734375 | 4 | # -*- coding:utf-8 -*-
'''
1.过滤掉用户输入中前后多余的空白字符:
' nick2018@qq.com '
2.过滤某windows下编辑文本中的'\r':
'hello world\r\n'
'''
'''
方法一:字符串strip(),lstrip(),rstrip()方法去掉字符串两端字符
方法二:删除行单个固定位置的字符,可以使用切片 + 拼接的方法
方法三:字符串的replace()方法或正则表达式re.sub()删除任意位置字符
方法四:字符串translate()方法,可以同时删除多种不用的字符
'''
# 方法一
s = ' nick2018 @qq.com ... |
3a01d18d97b6db3d35ce30c00969d02bd3d570db | hyena0608/CoTe | /유형/이진탐색/부품찾기/mycode.py | 609 | 3.5625 | 4 | # 이진
n = int(input())
arrN = list(map(int, input().split()))
m = int(input())
arrM = list(map(int, input().split()))
arrN.sort()
arrM.sort()
def binary_search(array, target, start, end):
if start > end:
return 'no'
mid = (start + end) // 2
if array[mid] == target:
return 'yes'
elif array[mid] > tar... |
db6fcfe266c6bfbca4497096422fa36168baf2e3 | CleanOceanAction/coa_flask_app | /coa_flask_app/db_accessor.py | 1,650 | 3.78125 | 4 | """
The module designed to contain all the database access logic.
"""
import os
import pymysql
class Accessor:
"""
This class is designed to contain all the database access logic.
"""
def __init__(self) -> None:
"""
The constructor of the Accessor class.
We create a databas... |
99d7e62b4fd6bf51cab40042b8fe237784bf6dc5 | EmilyOng/cp2019 | /perse_coding/round1_2018/q6_how_did_i_do.py | 135 | 3.546875 | 4 | a=['st','nd','rd','th','th']
for i in range(0,5):
name=str(input())
if name=="Ellie":
print("{0}{1}".format(i+1,a[i]))
|
81c55f6f6365d1e76aee6df558a57d156a1394a2 | wangdejun/PythonNotes | /Dic.py | 378 | 3.9375 | 4 | D = {'food':'bread','quantity':4}
print D
print D['food']
print D["food"]
Dic = {}
Dic['name']="Apple"
Dic['quantity']=2300
Dic['food']="Apple Pie"
print Dic
rec = {'name':{'first':'Bob','last':'Smith'},
'job':['dev','mgr'],
'age':40.5,
}
print rec
rec['job'].append('janitor');
rec['job'].append... |
6eaa6765b5d13cfd1d08ebc9c6a8c6d690acdc52 | itsyaboydatascience/StatsCalculator | /StatsCalc.py | 8,741 | 3.828125 | 4 | import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
def main():
#Main menu
data = pd.DataFrame()
menu()
choice = validate(7)
while choice != 7:
if choice == 1:
data = load()
menu()
choice = validate(7)
elif choice == ... |
f020555835fc7fb3cafd70c4f200e3f84448b56a | Dev-LeeMee/practice | /네이버부스트코스/모두를위한파이썬/연습/연습.py | 203 | 3.609375 | 4 | user1 = input('당신의 나이는? ')
user2 = input('당신의 이름은? ')
# print(user1)
# print(user2)
userid = int(user1) + str(user2)
print('당신의 아이디는 ', userid)
print('입니다.')
|
4bcfa63afd95d4bbe538714a19dc4f4cb3bd4331 | mesmerx/VelhaMaster | /velhamaster.py | 3,892 | 3.515625 | 4 | #!/usr/bin/env python3
import pprint
import os
from sys import platform
PLATAFORM = True if platform in ("linux", "darwin") else False
class VelhaG(object):
"""Docstring for MyClass. """
def __init__(self, player):
"""TODO: to be defined1. """
self.velhag = [" " for n in range(81)]
... |
9d19f08fb94ef0318241d62d0b3f4ca393f805e7 | joystonmenezes/python | /phy4.py | 159 | 4.28125 | 4 | str1=raw_input("Enter the string")
str2 = str1[::-1]
if str1 == str2:
print("Given string is palindrome")
else:
print("Given string is not palindrome") |
397119537f11b104885b13f8e61d908793a7b294 | wangyunge/algorithmpractice | /eet/Number_of_Islands.py | 1,575 | 3.78125 | 4 | '''
Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
Example 1:
11110
11010
11000
00000
Answer: 1
Example 2:
... |
5d07f3ca63cc71a678aed7a803fe6bff852c5f65 | JBustos22/Physics-and-Mathematical-Programs | /computational integrals/mymodules/numint.py | 3,084 | 3.71875 | 4 | #! /usr/bin/env python
"""
This is the numerical integration module that is used in other programs.
It includes: trapezoidal and simpson's method, their adaptive versions, and
a generalized n-dimensional monte carlo integration function.
Jorge Bustos
Mar 4, 2019
"""
from __future__ import division, print_function
imp... |
b8de637c40dc2f9a2b0d08df60f5a9f5e6bc9e81 | tmu-nlp/100knock2017 | /kurosawa/chapter01/knock02.py | 139 | 3.71875 | 4 | str1 = "パトカー"
str2 = "タクシー"
str3 = ""
l = len(str1)
for i in range(l):
str3 += str1[i]
str3 += str2[i]
print(str3)
|
7348e8a6ba879ef3e5fc6a58f3e7d7adfc713f36 | laeeqah/py-functions-cities | /py-functions-task1/functions-task-1-cities.py | 1,031 | 3.828125 | 4 | # Task 1
def hotel_cost(nights):
return 140 * nights
user_nights= int(input("Put in amount of nights: "))
print(hotel_cost(user_nights))
def plane_ride_cost(city):
if city == "Cape Town":
return 2500
elif city == "Durban":
return 2300
elif city == "JHN":
return 2000
... |
608a7941a9af0e772e811fb03c8103f89f66bc49 | ShabsSultana/Week1-Python-WIS | /Week1-Casting.py | 254 | 4.25 | 4 | product_name = input("What is the name of the product? ")
product_price = float(input("What is the price? "))
product_quantity = int(input("What is the quantity "))
total_price = str(product_quantity * product_price)
print("Total Price: " + total_price) |
cd689e11c107add0ca33ae8c6ff52eeb94f33ce5 | gokererdogan/AdaptiveMCMCwithPG | /target_distribution.py | 2,014 | 3.546875 | 4 | """
Learning data-driven proposals through reinforcement learning
This file contains the classes for representing target distributions.
13 Dec. 2016
https://github.com/gokererdogan
"""
import scipy.stats
import autograd.numpy as np
class TargetDistribution(object):
def __init__(self, data=None):
self.da... |
2632982fe835fb98495febbdbc0c3bcc6e69b532 | GitTeemu/PythonProgramming | /ope_10.6.py | 370 | 3.796875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 13 15:54:38 2018
@author: olli
"""
import random
arvattava = random.randint(0, 1000)
arvaus = 0
while arvaus != arvattava:
arvaus = int(input('Arvaa luku: '))
if arvaus < arvattava:
print('Liian pieni!')
elif arvaus > arvattava... |
6bc247a646cc2f4991d81cb97673925061a2e334 | meme2367/2021_1H_study | /dicoqnfkrzl/DFS&BFS/[2주차_고민정]_DFS&BFS_Lv3_여행경로.py | 2,213 | 3.578125 | 4 | #!/usr/bin/env python
# coding: utf-8
# - 정답
# In[8]:
DEPARTURE, DESTINATION = 0, 1
def func(answer, visited, tickets, count_route, now):
if count_route == len(tickets):
return True
else:
for idx, ticket in enumerate(tickets):
if not visited[idx] and ticket[DEPARTURE] == now:
... |
29411e63040c2cc803ad4717f74faec6359ee4d4 | Meghnakrishnan/programming-lab | /14.fun_sum.py | 635 | 4.3125 | 4 | #Write a Python function to sum all the numbers in a list.
n=int(input("enter number of elements in a list:"))#input number of elements in list
list=[] #initialise a list
for i in range(n): #to insert elements in list
numbers = int(input('Enter number '))
list.append(numbers)
def sumfun(list): #function... |
347ed143a732bb9cbcd5be2c9a283b2a0ebdb45b | keith-packard/aoc-2019 | /big.py | 4,374 | 3.5 | 4 | #!/usr/bin/snek
import random
def big_string(b):
return b[0] + b[:0:-1]
def big_equal(a,b):
if len(a) != len(b):
return False
for i in range(len(a)):
if a[i] != b[i]:
return False
return True
def big_uless(a,b):
if len(a) > len(b):
return False
if len(a) <... |
b9867a714f598768eef14f675bf475fb5b2c98e7 | h-kouame/2048 | /push.py | 3,698 | 3.90625 | 4 | ''' Kouame Kouassi
this module contains the core functions to play the 2048 game
It basically removes spaces and add the values vertically and horizontally
the algorithm consists in doing just for left and make use of symmetry
to do others'''
def push_up (grid):
"""merge grid values upwards by using the same conc... |
b147992ed48390dbb2ebaeb608911d838f32f737 | CobyHong/CPE-103-Cal-Poly-2017 | /Midterm/bst.py | 7,060 | 4.1875 | 4 |
#BSTNode is of:
# -value
# -left - another BSTNode
# -right - another BSTNode
class BSTNode:
def __init__(self, value, left, right):
self.value = value
self.left = left
self.right = right
def __eq__(self, other):
return ((type(other) == BSTNode)
and self.value == other... |
74521e3fb27b02ca1f783547e7619ce00e00bf08 | hikarocarvalho/Python_Wiki | /Exercises/01-Sequential-Structure/ex05.py | 372 | 4.3125 | 4 | # Get the value in meters
# pega valor em metros
meters = float(input("Enter the meters value to convert: "))
# Make a conversion from meters value
# converte metros em centimetros
centimeters =float(meters * 100)
# show the result from the conversion
# apresenta resultado da conversão
print(f"converting {meters} to ce... |
582c9827a0c0ed893b8a1df569d7239eee1be852 | vishnusak/DojoAssignments | /1-June-2016_Assignment/python/binarySearch.py | 1,180 | 4.15625 | 4 | # binary search
def binarySearch(arr, val):
start = 0
end = len(arr) - 1
found = False
pos = None
if arr[start] == val:
pos = start
elif arr[end] == val:
pos = end
else:
while ((end - start > 1) and (not found)):
print ("start is {}").format(start)
... |
f8a2487da9c238dc252112ccef06439ee9e14e3a | felipearaneda/aprendiendoPython | /ejercicio6.py | 317 | 3.921875 | 4 | """
#Ejercicio 6
Mostrar todas las tablas de multiplicar del 1 al 10.
Mostrando el título de la tabla y luego las multiplicaciones
"""
for titulo in range (1, 11):
print(f"########### Tabla del {titulo} ############\n")
for numero in range (1, 11):
print(f"{titulo} x {numero} = {numero*titulo}\n") |
3c1128e6ef738fdce38545a07d0274fa87bf0059 | erb13020/coursera-bioinformatics-specialization | /src/ApproximatePatternMatching.py | 640 | 3.78125 | 4 | from src import HammingDistance as hd
def approximatePatternMatching(pattern, genome, d):
'''
Find all approximate occurrences of a pattern in a string.
Input: Strings Pattern and Genome along with an integer d.
Output: All starting positions where Pattern appears as a substring of genome with at mos... |
fe7c2ffe1565f764064f5ac403773457733485b0 | prasannabe2004/PythonLearning | /coursera/InteractivePython/fundvalue.py | 677 | 3.6875 | 4 | # CodeSkulptor runs Python programs in your browser.
# Click the upper left button to run this simple demo.
# CodeSkulptor runs in Chrome 18+, Firefox 11+, and Safari 6+.
# Some features may work in other browsers, but do not expect
# full functionality. It does NOT run in Internet Explorer.
def future_value(presen... |
32f48e70e8179d280e68b679b12724a73a20cf91 | daviz888/python_works | /write_message.py | 473 | 4.0625 | 4 | from screen import clear
clear()
file_name = 'my_file.txt'
while True:
message = input("Please Enter your message:")
with open(file_name, 'a') as file_object:
file_object.write(message + "\n")
yes_no = input("\nDo you want to write new message? [N/Y] :")
if yes_no.upper() == 'N':
bre... |
0db18c0a2a374b642702ae1a2e393694d53f4cbe | padamcs36/Introduction_to_Python_By_Daniel | /Chapter 4 Selections/Ex_23_Point In Rectangle.py | 762 | 4.21875 | 4 | #Point in the rectangle or not
#width = 10(Horizontal), height = 5(vertical)
#A point is in the rectangle if its horizontal distance to (0,0) less than or equal to 10/2.
#A point is in the rectangle if its vertical distance to (0,0) less than or equal to 5/2.
#d = (x2 - x1 ) ^ 2 + (y2 - y1) ^ 2 ** 0.5
x2, y2 =... |
565661ca36870120a13c95f2dd1e77e40142174a | nickc96/Sudoku-Solver | /Final Project/sudoku.py | 8,415 | 3.59375 | 4 | import sys
import math
def generate(difficulty):
dif = validateDifficulty(difficulty)
if(not dif):
print("Invalid Difficulty")
else:
print(dif)
def update(grid):
for i in range(9):
for j in range(9):
i... |
6d2e37aa064a4255a08a84306fd237b2dcea2b39 | nyuxz/CodePractice | /415_Add_Strings.py | 2,345 | 4.15625 | 4 | # 415. Add Strings
'''
Detial about question:
'12345' + '6780'
12345
+ 6780
--------
19125
also we can reverse the string following,
54321
0876 +
------
52191
'''
from itertools import zip_longest
class Solution(object):
def addStrings(self, num1, num2):
"""
:type num1: str
:t... |
ac701b9ae8e8878927a90febf9c36271e2dc7086 | gajetto/scrypto | /scrypto/spiders/date.py | 736 | 3.515625 | 4 | from datetime import datetime
import sys
dates = ['9:20AM - 20 dec 2017','11:55PM - 12 jan 2018','8:09AM - 8 mar 2018', '11:55AM - 12 jan 2018', '8:20PM - 5 nov 2016', '6:08AM - 22 feb 2014']
def parseTime(argv):
timemap = list()
sorted_timemap = list()
for hours in argv:
time, date = hours.strip()... |
7ad9137f969dd5b93acff64012122c015997cb1e | midas87/WordCounts | /WordCounts.py | 204 | 3.859375 | 4 | # World count Exercise
print('Hi, What are you thinking off today?')
words = input()
worldCount = len(words.split())
print("Oh nice, you just told me what's on your mind in", worldCount, 'words!')
|
76763af9221ccfe0065e54a5eaa23dc189dd075f | ArchieDash/CodeWars | /letter_index.py | 248 | 3.9375 | 4 | import string
def alphabet_position(text):
alphabet = [str(letter) for letter in string.ascii_lowercase]
indexes = [alphabet.index(letter)+1 for letter in text.lower() if letter in alphabet]
return ' '.join([str(i) for i in indexes])
|
2d8f3a3599aae708c9b84c97023c5b90d928bd44 | KFurudate/Atcoder_SHOJIN | /Atcoder/20201004_くじかつ_112/D - Div Game.py | 424 | 3.65625 | 4 | from collections import Counter
def prime_fact(num):
prime = []
for i in range(2, int(num ** 0.5) + 1):
while num % i == 0:
prime.append(i)
num //= i
if num != 1:
prime.append(num)
return prime
n = int(input())
cnt = Counter(prime_fact(n))
ans = 0
for c in cnt.... |
009ceee63619b083a33efe7231db308763597f2a | robbierayas/zenva1 | /Crossy_RPG_Game.py | 1,940 | 3.71875 | 4 | # Pygame development 3
#draw objects to screen
# load images into objects
import pygame
#size of the screen
SCREEN_TITLE = 'Crossy RPG'
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 800
# colors according to RGB
WHITE_COLOR = (255, 255, 255)
BLACK_COLOR = (0, 0, 0)
# clock used to update game events
clock = pygame.time.Clock()... |
74fa1f49feacbf27be1e49db6df8de2f913b5a8c | anirudha-bs/Linux-Ram-cleaner | /ram_cleaner.py | 3,805 | 3.578125 | 4 | from tkinter import messagebox
from tkinter import simpledialog
from tkinter import *
import tkinter as tk
import os
def getpwd():
password = tk.simpledialog.askstring("Password", "Enter sudo password:", show='*')
return password
def clear(i):
password = getpwd()
bool=1
os.system("sync")
if ... |
4f6c041a7add85eb7fffa605e903c17c7e9ce2cc | hg-pyun/algorithm | /leetcode/binary-search-tree-to-greater-sum-tree.py | 1,525 | 3.703125 | 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 bstToGst(self, root: TreeNode) -> TreeNode:
m = [0 for _ in range(0, 100)]
s = [0 for _ ... |
34d53e383069d3acc84cbda5908a492f0849f8ce | Jason003/interview | /intuit/valid matrix.py | 1,906 | 3.5625 | 4 | def validMatrix(A):
if not A: return True
n = len(A)
correctSet = set(range(1, n + 1))
for i in range(n):
rowSet = set()
colSet = set()
for j in range(n):
rowSet.add(A[i][j])
colSet.add(A[j][i])
if rowSet != correctSet or colSet != correctSet:
... |
7e20ef36d3cb7ba480d6247430773cd30edb1664 | treno/project-euler | /euler_7.py | 1,652 | 4.21875 | 4 | """
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13 we can see that the 6th prime is 13.
What is the 10,001st prime number?
"""
# desired prime to find
GOAL = 10001
# arbitrary upper limit we'll use when searching for the desired prime
LIMIT = GOAL * (GOAL // 100)
# we store numbers and their "primeness"... |
66e255b64e5bdfa3f708c57d9364a1ebe67a9d33 | hagk17/MSSP-Python-Learning | /Homework1/PythonHW1 | 2,712 | 3.78125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 4 12:38:46 2020
@author: kathryn haglich
"""
##### QUESTION 1 #####
#### a [1,...,20]
a = list(range(1, 21))
print(a)
#### b [20,...,1]
b = a.copy()
b.reverse()
print(b)
#### c [1,...,19,20,19,...1]
c1 = a.copy()
c2 = b.copy()
c1.pop()
c = c1+c2... |
4b341711e77338a388d7540cfcb0470979420c12 | SrinuBalireddy/Python_Snippets | /Programs/RE.py | 4,612 | 4.21875 | 4 | # Write your code here :-)
"""
num= '222-333-4444'
#print(len(num))
print(num.partition('-'))
print(num[3])
def isphone(num):
if len(num)>=12 and num[3]=='-' and num[7]=='-' :
return True
else:
return False
print(isphone(num))
---------------------------------------------------
import re
r... |
a5e21837c4e183812de5c2da7577b4f7935f9db5 | json-tian/Competitive-Coding | /In Python/CCC13_J2_RotatingLetters.py | 183 | 4 | 4 | word = input()
accepted = True
for char in word:
if (not char in 'IOSHZXN'):
accepted = False
break
if (accepted):
print('YES')
else:
print('NO') |
9d96fed45fb9ce18c700c8bbbafbd2ff537decf9 | PhoenixDuarte/APPROJECT | /AP project.py | 920 | 4.0625 | 4 | import random
def guesscolour():
loop = True
gess = 0
print ("Guess what colour the program has selected. If you win, then the program stops. If you lose, you'll be trapped here forever.")
print ("Your options are: Black, White, Orange, Red, Yellow, Pink, Brown, Blue, Green, Cyan, and Gray.")
while ... |
14d7429796c9806cb562ae5da4f51f4f921862ad | amabirbd/automateTheBoringStuffs | /file1/file1practice.py | 3,710 | 3.671875 | 4 | import os
from pathlib import Path
hello = os.path.join('usr', 'bin', 'spam')
print(hello)
p = Path('spam', 'bacon', 'eggs')
print(p)
print(type(p))
myFiles = ['accounts.txt', 'details.csv', 'invite.docx']
for filename in myFiles:
print(Path(r'C:\Users\\user/hello', filename))
print(f'current working directory ... |
8bbb135b520e69d84ee41c1676932193f456de1d | lucasrachid/Lista-Estrutura-de-Dados-IFPR-1-Ano-1-Modulo | /Lista-03/ex-17.py | 265 | 3.90625 | 4 | numero = int(input('Diga um numero inteiro: ').strip())
if (numero > 0):
if (numero % 2 == 0):
print(f'O numero {numero} é par.')
elif (numero < 0):
print(f'O número é {numero}, somado 100 fica {numero + 100}')
else:
print('Dado inválido.')
|
49d438321d0bada9a4cd1b340a14e35202ffe489 | MLunov/Python-programming-basics-HSE | /Week 2: Conditional statement and while loop/2 (05).py | 337 | 3.734375 | 4 | xb = int(input())
yb = int(input())
xf = int(input())
yf = int(input())
if xf == xb - 1 and (yf == yb - 1 or yf == yb or yf == yb + 1):
print('YES')
elif xf == xb + 1 and (yf == yb - 1 or yf == yb or yf == yb + 1):
print('YES')
elif xf == xb and (yf == yb - 1 or yf == yb + 1):
print('YES')
else:
... |
66a98d9609f666676a14ed5e9303072a36e45ae2 | Uche-Clare/python-challenge-solutions | /Uche Clare/Phase 2/String/Day 31/Task 3.py | 247 | 4.15625 | 4 | #Write a Python program to remove a newline in Python.
string = "The quick brown fox jumps over the lazy dog.\nThe quick brown fox jumps over the lazy dog."
print(string)
string= string.replace('\n', " ") #Remove a newline
print(string) |
473f1c8fe95859ce9020a12b8d64689aaafd31dc | Turboklau/Onitama | /Robots/FirstFinley.py | 1,025 | 3.546875 | 4 | class FirstFinley:
def decide_move(self, board, me, robotinfo):
"""First Finley always takes the first legal move he can find"""
# Inverts movement matrix if playing for opposing side
mult = 1
if me == 1:
mult = -1
my_hand = robotinfo.get_hand(me)
# Fo... |
6c22e5705147e14fa23712747531fb7875a68eee | RichardSefton/LotteryPredictor | /Algorithms/EuroMillionsFreq.py | 3,645 | 3.5 | 4 | import numpy as np
from Arrays import EuroMillionsArrays as ema
# define the arrays to be used
mainFreq = ema.mainNumberFreq
luckFreq = ema.luckyStarFreq
mainSeq = ema.mainNumberSequence
luckSeq = ema.luckyStarSequence
luckFreqWeight = ema.luckyStarWeighted
zippedMain = zip()
zippedLuck = zip()
mainWeights ... |
c98e3c98515b94e354f52239c293cbc9ab7b4e32 | hellock/icrawler | /icrawler/storage/base.py | 810 | 3.796875 | 4 | from abc import ABCMeta, abstractmethod
class BaseStorage:
"""Base class of backend storage"""
__metaclass__ = ABCMeta
@abstractmethod
def write(self, id, data):
"""Abstract interface of writing data
Args:
id (str): unique id of the data in the storage.
data ... |
7321d69757c8d8f7d38ccc2b698c40e18dd96646 | deleyva/book2-exercises | /myapifilms/get_movies.py | 1,235 | 3.5625 | 4 | # GET data from My API Films, parse, and write to database
import json
import requests
import sqlite3
TOKEN = 'ADD YOUR TOKEN'
url = requests.get('http://api.myapifilms.com/imdb/inTheaters?token={0}&format=json&language=en-us'.format(TOKEN))
# convert data from feed to binary
binary = url.content
# decode the jso... |
b76bcda62753980ee6a36ced1fb51e692c8d657b | Fryzu/DesignPatterns | /observer/subscribers.py | 578 | 3.609375 | 4 | from abc import ABC, abstractmethod
import datetime
class Observer(ABC):
@abstractmethod
def update(self, updateData: datetime.date):
pass
class DayMonthYear(Observer):
def __init__(self, subject: 'Subject'):
subject.register(self)
self._actualDate = '-'
@property
def date... |
8782603c2c54e8dd5791c75ce9c96dc83c478951 | algo-morning-group/algo_and_ds | /binary_search/nearest.py | 727 | 3.75 | 4 | def binary_search_nearest(arr, target):
if len(arr) == 0:
return -1
b = 0
e = len(arr) - 1
while b + 1 < e:
m = b + (e - b) // 2
if arr[m] == target:
return m
if arr[m] < target:
b = m
else:
e = m
return b if abs(arr[b] ... |
dffc3a3627a313a2ed68efc64be6087699c259ee | FlagArihant2000/IvLabs | /python/python/program5.py | 458 | 4.125 | 4 | #Write another program that prompts for a list of numbers as above and at the end prints put both the maximum and minimum of the numbers instead of the average
numbers = []
i = 0
while True:
try:
number = input('Enter a number: ')
if(number == 'done'):
break
else:
number = int(number)
except ValueError:
... |
239b0cde9db4e3d1a4b67308be107d14b99455dc | vikaskharkwal/Terminal-Tac-Toe | /game/main.py | 1,670 | 3.5625 | 4 | import valuecheck
import humiliation
import vs2player
import vscpu
import namechange
print("Welcome to Terminal-Tac-Toe.")
choice = input("\nEnter a number depending on your choice: \n1. Play\n2. Instruction \n3. Quit\n")
choice = valuecheck.value_check(choice)
if choice == 1:
choice = input("\nWho do you want to b... |
7b52d1ae89bf9f92ca2091d359a2c16839b20831 | ShangtongZhang/ShangtongZhang.github.io | /assets/pdf/cs_4501_fall_23/assignment1/solution.py | 879 | 4 | 4 | import numpy as np
class NewtonException(Exception):
"""
A class to throw when the second order derivative is zero.
"""
def __str__(self):
return str('second order derivative is zero')
class Newton(object):
def __init__(self):
pass
def minimize_f1(self, x0, n):
'''
... |
a1f464320bfe35595e26dd857807bac3f73906ca | danielsunzhongyuan/python_practice | /thread/producer_consumer_1.py | 1,123 | 3.75 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import Queue
import random
import thread
import threading
import time
share_queue = Queue.Queue()
my_lock = thread.allocate_lock()
class Producer(threading.Thread):
def run(self):
products = range(5)
global share_queue
while True:
... |
1d5df052bdcbf79f70252b8683748371a985cd05 | fengbaoheng/leetcode | /python/404.sum-of-left-leaves.py | 862 | 3.5 | 4 | #
# @lc app=leetcode.cn id=404 lang=python3
#
# [404] 左叶子之和
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# 不断递归,栈中记录节点
def sumOfLeftLeaves(self, root: TreeNode) -> int:
if root is None:
return 0
... |
73537a38839cdaa7032dacbb9cef86fe4d591eb4 | EdCarlosBicudo/UH-Data_analysis_with_Python | /hy-data-analysis-with-python-summer-2021/part01-e12_distinct_characters/src/distinct_characters.py | 229 | 3.546875 | 4 |
def distinct_characters(L):
result = {}
for i in L:
result[i] = len(set(i))
return result
def main():
print(distinct_characters(["check", "look", "try", "pop"]))
if __name__ == "__main__":
main()
|
419329360a1d6b205447d9eab3e876558d10ccb8 | MistahBigB/Questions-for-Mike | /guess.py | 2,873 | 4.5 | 4 | #guess.py
# Lab 8: Guess the Number
'''
Let's play 'Guess the Number', the computer will choose a random int between 1 and 10. The user will then try to guess the number, and the program will tell them whether they're right or wrong.
## Advanced Version 1
Tell the user whether their guess is above ('too high!'... |
1b119523a8ca7183377c1628d3275c56c3b9a696 | rafaellamgs/prog_comp2018.1 | /aula04_10/explicacao.py | 291 | 3.78125 | 4 | texto = input('Informe um texto: ')
print(texto)
qt_caracteres = len(texto)
print(qt_caracteres)
texto_invertido = ''
contador_letras = 0
while contador_letras < qt_caracteres:
texto_invertido = texto[contador_letras] + texto_invertido
contador_letras += 1
print(texto_invertido)
|
c1cb4b00716d5c677a1af02dab3e29eb71680227 | aos/advent | /2018/day11/kadane.py | 962 | 4.1875 | 4 | # Sidebar: Kadane's algorithm for finding maximum subarray sum
# This is a very good simple intro into dynamic programming!
# Given array: [1, -2, 3, 5, -5]
# The maximum subarray sum is 8 ([3, 5])
def kadane(array):
global_sum = local_sum = 0
for item in array:
local_sum = max(item, local_sum + item... |
b1c2673def57466570db2b9b24525cffb702d774 | kalyanchatterjee/python_learning | /tuples.py | 245 | 4.21875 | 4 | point = (1, 2, 3) + (4, 5, 6)
print(point * 3)
# Convert an iterable to tuple
other_point = tuple([1, 2])
print(other_point)
another_point = tuple("Hello World")
print(another_point)
# Unpacking
x, y, z = (3, 4, 9)
print(x)
print(y)
print(z)
|
f294673b2ebb2eedbf2d8ac78edd95950d750b6f | fhwid/Python-100-Days | /Day01-15/code/Day12/test_str1.py | 558 | 4.15625 | 4 | """
check the username and QQ number
"""
import re
def main():
username = input('Pls input the username:')
qq = input('Pls input the QQ number:')
# the first Arg of match is re expr
# the second Arg is the string to be matched
m1 = re.match(r'^[0-9a-zA-Z_]{6,20}$', username)
if not m1:
... |
6275d9d1a12b89ee34bc37056614bff17181f38c | WayneChen1994/Python1805 | /day06/可迭代对象.py | 824 | 4.21875 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# author: Wayne.Chen
'''
可迭代对象:
能作用于for循环的,我们统称为可迭代对象
本质是复写了__iter__
1、常见的可迭代对象:
list/tuple/set/dict/range/str
2、生成器:可以一边循环一边推算出下一个元素
像这样的机制我们称为生成器【优点:节约内存】
'''
'''
如何创建生成器?
将列表生成式的[]改为(),则就为生成器
'''
from collections import Iterable
list1 = [x for x in range(1, 101... |
beb4f973abd368cad4a18b5da0bf584ff9f7c40f | mahimadubey/leetcode-python | /jump_game_ii/solution3.py | 1,104 | 3.90625 | 4 | """
Given an array of non-negative integers, you are initially positioned at the
first index of the array.
Each element in the array represents your maximum jump length at that
position.
Your goal is to reach the last index in the minimum number of jumps.
For example:
Given array A = [2,3,1,1,4]
The minimum number ... |
1f60120b6cccdf3e34d8b11029c3f8a05091bec2 | vikulovm5/Homeworks | /ДЗ_1Спорт.py | 294 | 3.796875 | 4 | a = int(input("Введите расстояние в первый день: "))
b = int(input("Введите целевой результат: "))
day = 1
while a < b:
a = a * 1.1
day = day + 1
print(f"На {day}-й день результат составил более {b}км") |
3b8a5b45fd296478508b3140ad3596433c5f1fde | ShoeRider/UTTT_Analitics | /Base/ExpressiveSystem/Py_Methods/Python_Example/MCHS.py | 1,275 | 3.65625 | 4 | #Using the Sieve of Eratosthenes Prime method
# This is Much faster than brute force.
#BigO(n^2)
def CreatePrimeList(Range):
# list of our range, starting with 0's indicating primes
# When we add a prime to our Prime List, we mark all multiples of that number larger than Prime*Prime
IntegerList = [0 for X in ra... |
ff07c122e87193ccaa8c037fa3fb8fdeff1a6854 | Iverance/leetcode | /333.Largest BST Subtree.py | 1,248 | 4.0625 | 4 | """
Given a binary tree, find the largest subtree which is a Binary Search Tree (BST), where largest means subtree with largest number of nodes in it.
Note:
A subtree must include all of its descendants.
Here's an example:
10
/ \
5 15
/ \ \
1 8 7
The Largest BST Subtree in this case is the highlig... |
23d242e6b7f202cb22289eeedc77382a23389d16 | ttund21/LearningPython | /PythonBrasilExercicios/EstruturaDeRepeticao/Respostas/20_Questao.py | 425 | 3.921875 | 4 | # 20. Altere o programa de cálculo do fatorial, permitindo ao usuário calcular o fatorial várias vezes e limitando o fatorial a números inteiros positivos e menores que 16
while True:
fatorial = 1
try:
num = int(input('Número: '))
except ValueError:
break
if num > 16 or num < 0:
... |
71abc1a53b1a00f0f9dc13e56b17921398c5bf8e | yijoon009/PYTHON | /03일차.py | 2,943 | 4.1875 | 4 | '''
형변환
데이터의 형태를 변환
ex) 1->'1'
str(1) = 정수를 문자열로 형태를 변환
str(데이터) : 문자열로 변환
int(데이터): 정수로 변환
float(데이터): 실수로 변환
>>> float_number=float(100)
>>> type(float_number); print(float_number)
<class 'float'>
100.0
문자열 함수
upper(): 대문자 변경
변수명.upper()
lower(): 소문자 변경
--> upper, lower 전부 기능이라 저장해야해.
replace(): 문... |
4fde2539d87f3c363e2d9f507b3b76770319e847 | Aasthaengg/IBMdataset | /Python_codes/p00003/s349771674.py | 416 | 3.6875 | 4 | #1???????????????
num_data = int(input())
for i in range(num_data):
input_line = input().split(" ")
a = int(input_line[0])
b = int(input_line[1])
c = int(input_line[2])
#?????????????????????????????????????????§
if (pow(a,2) + pow(b,2) == pow(c,2) ) or (pow(a,2) + pow(c,2) == pow(b,... |
1049599030cf01a9738d23cfa7cc211b50a79460 | greenfox-zerda-lasers/gygabor | /week-04/day-3/4.py | 493 | 4.28125 | 4 | # create a 300x300 canvas.
# create a line drawing function that takes 2 parameters:
# the x and y coordinates of the line's starting point
# and draws a line from that point to the center of the canvas.
# draw 3 lines with that function.
from tkinter import *
root = Tk()
canvas = Canvas(root, width = 300, height = 30... |
ccc3ce13b404ffaea3fd4355b27a9f16a92e9522 | christian-alexis/edd_1310_2021 | /tarea_4.py | 4,617 | 3.5 | 4 | class Array:
def __init__(self,tam):
self.__arreglo=[]
def leer(self):
archivo = open("archivo.txt","r")
for linea in archivo.readlines():
for linea1 in linea.split(","):
self.__arreglo.append(linea1)
... |
33633dace3e9ecefce51449224a653b9c516e07e | suhaslucia/100-Days-of-Python | /04. Day 04 - Pizza Ordering .py | 885 | 4.28125 | 4 | # Printing the Heading
print(" ----- Pizza Ordering ----- ")
# Taking the inputs from the user for size, topping, cheese of the pizza
size = input("Enter the Size of the pizza 'S', 'M', 'L': ")
topping = input("Do you want Pepperoni ? 'Y', 'N': ")
cheese = input("Do you want Cheese ? 'Y', 'N': ")
bill = 0
# Checking ... |
f6dd95cd78b7bdff2e929bac6ee29b0f42790d1f | linkz73/keras | /keras12_ensemble2.py | 4,247 | 3.578125 | 4 | # input 2 -> output 3
#1. 데이터
import numpy as np
x1 = np.array([range(100), range(311,411), range(100)])
x2 = np.array([range(100, 200), range(311,411), range(100,200)])
y1 = np.array([range(501, 601), range(311,411), range(100,200)])
y2 = np.array([range(501, 601), range(711,811), range(100)])
y3 = np.array([range(... |
47dbd1239182a0116e586434632ff7a4a9e98b04 | mini-ray/python | /ProjectStem/code3.5.py | 202 | 4.03125 | 4 | g = int(input("What grade are you in? "))
if g == 9:
print("Freshman")
elif g == 10:
print("Sophomore")
elif g == 11:
print("Junior")
elif g == 12:
print("Senior")
else:
print("Not in High School") |
b936ed8661a44e34c0b94ede06e51c0029b4f9b8 | ivn-svn/Python-Advanced-SoftUni | /Tuples-Sets/Exercises/02. sets_of_elements.py | 439 | 3.90625 | 4 | #create a func to find num of elements in each set
def find_numbers():
nums = tuple(map(int, input().split()))
return nums
def fill_set(count):
s = set([])
for _ in range(count):
s.add(input())
return s
def find_intersection(s1, s2):
result = s1.intersection(s2)
for el in result:
... |
ad9b3929d02433b561e5d484ca68d3b32ff94ed9 | zopepy/leetcode | /palindrome_pairs.py | 845 | 3.515625 | 4 | class Solution:
def palindromePairs(self, words):
"""
:type words: List[str]
:rtype: List[List[int]]
"""
def build_hashs(cur):
l = len(cur)
i = l
ans = []
while i>0:
curp = cur[i:]
if curp == curp... |
3b9493ef4c0f375c7e03fe1cb962615213329c5b | khadtareb/class_assignments1 | /pythonProject6/Assignment_48.py | 212 | 3.5 | 4 | #Python program for removing i-th character from a string
s='123456'
#s1=''
n=int(input(":"))
# for i in range(len(s)):
# if i!=n:
# s1=s1+s[i]
# print(s1)
s1=s.split(s[n])
s2=''.join(s1)
print(s2) |
cfafbe01d2849bf9e6e22e18eb53178611467e8a | Troys-Code/Coding | /SelfStudy[Python]/Learn_Python/Into_to_Lists/motorcycles_pop_and_remove_by_val.py | 1,159 | 3.796875 | 4 | motorcycles = []
motorcycles.append('wr250x')
motorcycles.append('r6')
motorcycles.append('cbr')
motorcycles.append('zx6r')
motorcycles.append('hypermotard')
motorcycles.append('gsxr')
print("\nMotorcycle List:")
print(motorcycles)
#popped_motorcycle = motorcycles.pop() # Pop removes the last item in the list while ... |
c9015335226b5daf3b1e8332ef2ee105cd91dfbd | sdemoya/py-scripts | /classes/user_class2.py | 1,739 | 4.03125 | 4 | class User:
"""Models typical user information."""
def __init__(self, username, first_name, last_name, email, age):
"""Initialize attributes to describe a user."""
self.username = username
self.first_name = first_name
self.last_name = last_name
self.email = email
... |
8cace7eb6c4240b5069dd5d318e5c0ea9d4b7926 | shlokKh/interview-practice | /chapter4/p8.py | 803 | 3.53125 | 4 | class Node:
def __init__(self, x):
self.x = x
self.left = None
self.Right = None
#r = root, v1 = val1, v2 = val2
def first_common_ancestor(r, v1, v2):
if not covers(r, v1) or not covers(r, v2):
return None
return first_common_ancestor_aux(r, v1, v2)
def first_... |
179f67ce28557dee44a5fd52d63ffb8737d65cc5 | asher-lab/Python-for-DevOps-Learn-Ruthlessly-Effective-Automation | /Chapter_3_Working_with_the_command_line/sys_argv.py | 311 | 3.640625 | 4 | #!/usr/bin/env python3
"""
Simple command-line tool using sys.argv
"""
import sys
if __name__ == '__main__':
print(f"The first argument: '{sys.argv[0]}'")
print(f"The second argument: '{sys.argv[1]}'")
print(f"The third argument: '{sys.argv[2]}'")
print(f"The fourth argument: '{sys.argv[3]}'")
|
86d2c3f321f1ef88814f8181b89dacb3c846ed7c | lucasmccabe/Neuron-Simulations | /Izhikevich.py | 1,372 | 3.6875 | 4 | #simulates a neuron using the Izhikevich model
from numpy import linspace
import seaborn as sns
import pylab as pl
#request user input for the current
I = float(input('Enter an input current (nA): '))
#initialize properties of the neuron
dt = 0.05 #time increment
sim_time = 30 #simulation time in ms
time... |
cfe6141e240c4b250a6ac75c71bafba00936e8fc | jChapman/advent-of-code-2019 | /02/solution2.py | 2,515 | 3.59375 | 4 | class IntCode:
ADD = '1'
MULT = '2'
END = '99'
def __init__(self, input):
if isinstance(input, str):
self.instructions = input.split(',')
else:
self.instructions = input
def int_at(self, idx):
return int(self.instructions[idx])
def assig... |
68d08ea421674cb3df8d3e755c2689b89ec7d809 | simplesmall/Python-FullStack | /Day0625/Day25_8反射.py | 1,333 | 3.515625 | 4 | # if hasattr(handler,val)
# getattr(handler,val)
class Foo(object):
country = '中国'
def func(self):
pass
obj = Foo()
v = getattr(Foo, 'country')
print(v)
v1 = getattr(Foo, 'func') # Foo.func 根据字符串为参数,去类中寻找与之同名的成员
print(v1)
v = getattr(obj, 'func') #obj.func 根据字符串为参数,去对象中寻找与之同名的成员
p... |
00bc378854c06db624fe294bb7e51200170d3de0 | suchishree/django_assignment1 | /python/looping/assignment2/no7.py | 143 | 4.125 | 4 | # W.A.P to print 1 to n, 5 divigibles
maximum = int(input("enter your maximum value:"))
for x in range(5, maximum+1, 5):
print(x, end=" ") |
fc5e8a61af84549d2e37d6c2f80bdb4dd3f96c09 | heliormarques/labprog2019.2 | /paper.py | 840 | 3.625 | 4 | #mudar a entrada aqui
lista = [20,5,10,5,15,15,15,5,6,22];
def cortar(lista, corte):
anterior = '0';
atual = '0';
total = 1;
cortou = False
for retangulo in lista:
if retangulo > corte:
atual = 'acima';
cortou = True;
else:
atual = 'a... |
7e8e442e5eb21bc3e57ed6c798b277439d37f8bd | LeaBranch/python3 | /Reindent/Reindent.py | 1,338 | 3.640625 | 4 | import sys
def myCountFunc(str, lec):
s = 0
for i in range(len(str)):
if (str[i] == lec):
s += 1
else: break
return s
argc = len(sys.argv)
# получение имени файла
if (argc != 2):
print('Usage: ' + sys.argv[0] + ' <filename>')
exit(1)
name_p = sys.argv[0]
name_f = sys.argv[1]
# открытие и чтение кода
w... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.