blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
a39820f66c16c5d55977260839702ecae9afc2a2 | HummingMaster/Learning-Python3 | /fibonaccie_list.py | 461 | 4 | 4 | import random
size_ = int(input("Enter size: "))
def fibonacci(size):
fib_ls = []
for number in range(0, size + 1):
fib = (((1 + 5 ** 0.5)/2) ** number - ((1 - 5 ** 0.5)/2) ** number)/5 ** 0.5
fib_ls.append(fib)
print(fib_ls)
fibonacci(size_)
def rand_fibonacci(number):
fib = (((1 ... |
0c32818dafb58891d3563bf1b7d01f8e8ceb1ee3 | dae-ne/ConnectFour_Python | /connect_four.py | 17,971 | 3.515625 | 4 | import numpy as np
import random
from tkinter import font as tkfont
from tkinter import messagebox
import tkinter as tk
BOARD_SIZE = (600, 700) # (y, x)
GAME_FIELDS = (6, 7) # (y, x)
PLAYER_FONT_SIZE = 32
MENU_FONT_SIZE = 52
GAME_BACKGROUND_COLOR = "white"
GAME_FOREGROUND_COLOR = "black"
GAME_ACTIVE_BU... |
4bd6b8c94e151d88e676ba1baf436426ae13bc39 | ZbigniewPowierza/pythonalx | /petle/przyklady_while.py | 499 | 3.578125 | 4 | # losowanie
import random
print(dir(random))
print(help(random.randint))
print(random.randint(1,10)) #loduje liczbę całk. z przedziału od 1 do 10
gracz_x = random.randint(1, 10)
gracz_y = random.randint(1, 10)
skarb_x = random.randint(1, 10)
skarb_y = random.randint(1, 10)
print("Połozenia gracza", gracz_x, gracz_... |
ff9428d80db7919ff90269500ea70ff6f97a3949 | ymanzi/42bootcamp_machine_learning | /module05/ex02/TinyStatistician.py | 1,277 | 3.59375 | 4 | from math import sqrt
from math import pow
class TinyStatistician:
def __init__(self):
from math import sqrt
from math import pow
def mean(self, x):
if len(x) == 0:
return None
mean = float(0)
for elem in x:
mean += elem
return float(mean / len(x))
def median(self, x):
if len(x) == 0:
retu... |
7a6730b86482e8ef0125f374f68ff2d08cfebf65 | zegster/jalapeno-hotties | /wordCounter/word_count_w_graph_v2.py | 4,838 | 3.625 | 4 | """
Program Description: This program is designed to read read the rules file created by the make__codebook.py file
and find the patterns described in the rules.txt file. This information is then shown on a graph for the user.
Author: Bekzod Tolipov, Duc Ngo, Enrique Casillas, Lawrence C, Joel A
Date:... |
1b2c3ea362c4b373bc04ec04140aced9e90b4a83 | barbarasidney/cours | /Coursera_Python for everybody/Cours1_Programming for Everybody_Getting Started with Python/Cours1_Week5.py | 1,718 | 4.28125 | 4 | # Week 4
# Write a program to prompt the user for hours and rate
# per hour using input to compute gross pay.
# Pay the hourly rate for the hours up to 40 and 1.5 times
# the hourly rate for all hours worked above 40 hours.
# Use 45 hours and a rate of 10.50 per hour to test the program
# (the pay should be 498.75). ... |
6fafa89090f526c6b7cb9f9b528d0b31eba4e03f | walkerwell/algorithm-data_structure | /src/main/python/codeforces/run_118A.py | 156 | 3.65625 | 4 | s=raw_input().lower()
res=''
for i in range(len(s)):
if s[i] not in ['A','a','O','o','Y','y','E','e','U','u','I','i']:
res+='.'+s[i]
print(res)
|
e4293535584ef31b2c671c5b155d28c73f7e2834 | MichalBrzozowski91/algorithms | /leetcode/medium/1315_Sum_of_Nodes_with_Even-Valued_Grandparent.py | 1,125 | 3.640625 | 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 sumEvenGrandparent(self, root: TreeNode) -> int:
def helper(root,flag1,flag2):
... |
bd30853765c08a2ecbe8731938189e2f46b605f9 | Rickym270/rickym270.github.io | /data/projects/InterviewStudying/Easy/SortedSquaredArray/Practice13.py | 537 | 3.8125 | 4 | #!/usr/bin/python3
array = [-9, -5, 0, 1, 4, 8]
def sortedSquaredArray(array):
array.sort()
lp = 0
rp = len(array) - 1
sorted_squares = [0 for _ in array]
for idx in reversed(range(len(array))):
if abs(array[lp]) > abs(array[rp]):
sorted_squares[idx] = array[lp] ** 2
... |
41707d6eba1ab2ad9239d151b1709cbe4485d0c1 | brie23/temperature_conversion | /fahrenheit_to_celsius.py | 336 | 4.25 | 4 | def temperature_conversion():
print("This program will convert Fahrenheit to Celsius.")
print("Please enter the temperature in degrees Fahreneheit: ")
fahrenheit = int(input())
celsius = (fahrenheit - 32) * 5 / 9
print("This converts to approximately " + str(celsius) + " degrees Celsius.")
temperat... |
e7c502520a0bb67daec0c0925caba8a089e33f44 | zelaznik/scratchpad | /App-Adademy/coding_interview_questions/triple_sum/test.py | 2,979 | 4.03125 | 4 | import unittest
from main import *
"""
###################################################
Unit test the helper methods for the function
################################################### """
class Test_get_index_pairs(unittest.TestCase):
def test_zero_returns_empty_sequence(self):
expected = ()
... |
83de168040a2f49c5456c4be346597986f346e4b | manthan787/algo-practice | /graphs/number_of_islands.py | 3,092 | 3.546875 | 4 | '''
Problem: https://leetcode.com/problems/number-of-islands/description/
Similar code, without any graph datastructure is in `number_of_islands_2.py`.
Interestingly, this code isn't accepted by leetcode, since it exceeds time limit.
I suspect that is due to creating a graph and keeping it in memory. The alternative
s... |
e64359554cafc3ebfc2709848d96258cba6ee0f4 | Durga944/python_qus | /Ques2.py | 152 | 3.859375 | 4 | day=raw_input(" enter a day")
if day == "monday":
print"poha"
if day == "tuesday":
print"maggi"
if day == "wednesday":
print "parata"
|
9ef5ab50abeb2d13db448f12c00186b83ca04a08 | justanotheratom/Algorithms | /Python/Tree/BinaryTree/binarytree.py | 2,982 | 3.984375 | 4 | from .queue import Queue
from .stack import Stack
class Node(object):
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def is_leaf(self):
return (self.left is None) and (self.right is None)
class BinaryTree(object):
def __init__(self, root)... |
4cebbedaf748e2316d385899010ecc68961950ba | noname2048/programers | /월간_코드_챌린지_시즌1/02_3진법_뒤집기.py | 684 | 3.90625 | 4 | n = 19
def solution(n: int) -> int:
tmp = ""
while n >= 3:
n, r = divmod(n, 3)
tmp += str(r)
else:
tmp += str(n)
return int(tmp ,3)
m = solution(n)
print(m)
"""
n = 19
def solution(n: int) -> int:
number_list = list()
while n >= 3:
r = remainder = int(n % 3... |
2a614545e97639d64f312f19566d699cbb13a589 | LeeSangJun/pythonStudy | /20170420/example01.py | 2,159 | 3.71875 | 4 | __author__ = 'leesangjun'
#컴프리헨션 : 하나 이상의 이터레이터로부터 파이썬의 자료구조를 만드는 콤팩트한 방법
#1~5까지의 정수 리스트를 만드는법
number_list = []
number_list.append(1)
number_list.append(2)
number_list.append(3)
number_list.append(4)
number_list.append(5)
print(number_list)
#range함수를 이용
number_list = []
for number in range(1, 6):
number_list.app... |
e6853b9e265c0642e32460fdcf4ad0cb02b6f33c | DragnSlav3/MisionTIC-2022-Universidad-Nacional-de-Colombia | /Ciclo 1/Otros códigos/Copiados/ColorMarte_Astrid (función recursiva, ejercicio en clase).py | 227 | 3.859375 | 4 | def color_marte(n=3):
entrada=input("Ingrese color: ")
if entrada.lower() =="Rojo".lower():
print("Ganaste")
elif n == 1:
print("Perdiste :(")
else:
color_marte(n-1)
color_marte()
# Código de Stefany Gordillo |
08db83a4f044995d61b07a3102763f29bafb8d24 | jthiruveedula/PythonProgramming | /Regex/patternCaret.py | 517 | 4 | 4 |
#caret is used to search the string from strating position
import re
pattern='^I'
string = '''I am black!
I am swinging in the sky,
I am wringing worlds awry;
'''
match =re.match(pattern,string)
search =re.search(pattern,string)
findall =re.findall(pattern,string)
print("Match Method: " ,match)
print("Search Method... |
36a1d4482a9ca4e917d5cffce4565d49b93d360f | CodeHemP/CAREER-TRACK-Data-Scientist-with-Python | /12_Intermediate Data Visualization with Seaborn/03_Additional Plot Types/03_barplots, pointplots and countplots.py | 1,137 | 3.765625 | 4 | '''
03 - barplots, pointplots and countplots
The final group of categorical plots are barplots, pointplots and
countplot which create statistical summaries of the data. The plots
follow a similar API as the other plots and allow further customization
for the specific problem at hand
'''
# 1 - Countplots
# Cr... |
21de4b69dde58766581fdfaa5838844d60902963 | Luciano-JeonHyunJun/Baekjun_No1 | /1000.py | 185 | 3.515625 | 4 | a,b = input().split()
a = int(a) #a는 int인걸 알려주는것
b = int(b) #''
print(a+b) #a+b
#split은 문자열을 짤라서 리스트로 만들어주는 함수입니다 |
029939c468fa36f728a534433be8bd550661e76e | Mayank2134/100daysofDSA | /CN DSA/swapNodeLL.py | 1,010 | 3.859375 | 4 | class Node:
def __init__(self, data):
self.data = data
self.next = None
def makeLL(arr):
if len(arr) == 0:
return None
head = Node(arr[0])
curr = head
for i in range(1, len(arr)):
curr.next = Node(arr[i])
curr = curr.next
return head
def printLL(head):... |
6b05cd7833f8d32f4cfe90c76371d734f7f0e6a2 | jmbotero/algorithms | /basics.py | 1,361 | 3.78125 | 4 | # region Algorithm's Introduction
def generaterandomstring(mask, bestmatchstring):
alphabet = "abcdefghijklmnopqrstuvwxyz "
result = ""
for i in range(len(mask)):
char = ""
if not mask[i]:
char = alphabet[random.randrange(len(alphabet))]
else:
if bestmatchstri... |
cd607600b11e795d1ba0350aa35e86546357024f | atomextranova/leetcode-python | /BFS/BinaryTree/Deserialize binary tree/deserialize.py | 3,075 | 4 | 4 | class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
from collections import deque
class Solution:
"""
@param root: An object of TreeNode, denote the root of the binary tree.
This method will be invoked first, you should design your own algorithm
... |
f8c5cfc34baa994563c6e2eaa7e533523c71831a | vvalleru/leetcode-solutions | /ExcelSheetColumnTitle.py | 240 | 3.59375 | 4 | class Solution:
# @return a string
def convertToTitle(self, num):
result = ''
while num > 0:
num -= 1
result = chr(65 + num % 26) + result
num /= 26
return result |
144bf890eff142c3a35d81b38493b23f294a4cee | FaezehAHassani/python_exercises | /syntax_class_game.py | 6,948 | 4.03125 | 4 | # how to write a test
# first make a tree like below
#* Map
# - next_scene
# - opening_scene
#* Engine
# - play
#* Scene
# - enter
# * Death
# * Central Corridor
# * Laser Weapon Armory
# * The Bridge
# * Escape Pod
# then add a litte test as the end
from sys import exit
from random import randi... |
5a2bb6cbe3f7e38d4a2680708bdb171c9f724bd4 | SoyeonHH/Algorithm_Python | /baekjoon/2562.py | 162 | 3.53125 | 4 | nums=[]
while True:
try:
num = int(input())
nums.append(num)
except:
break
print(max(nums))
print(nums.index(max(nums))+1) |
1ab0e458c62947d59578f213ec2a863ec880c274 | 5imyboy/Chinese_Chess | /board.py | 3,659 | 3.9375 | 4 | """
board.py
draws the board
"""
import pygame
BOX_SIZE = 60
SCREEN_HEIGHT = 600
SCREEN_WIDTH = 800
board_arr = []
class BoardPos:
""" object in board array """
def __init__(self):
self.is_occupied_red = False
self.is_occupied_blue = False
def is_occupied_none(self):
""" true iff... |
00c515d1108364cb903e92aeb02b287c954119f7 | sandrahelicka88/codingchallenges | /Google/pow.py | 741 | 4.28125 | 4 | import unittest
'''Implement pow(x, n), which calculates x raised to the power n (xn).'''
def myPower(x,n):
if n == 0:
return 1
elif n<0:
return 1/myPower(x,-n)
elif n%2:
return x * myPower(x, n-1)
else:
return myPower(x*x, n//2)
print(myPower(3,3))
class Tes... |
9a9cfb682e8b75e31e3b3386c64fc8b5b9623e6c | 1dataplease/courses | /python-courses/An Introduction to Interactive Programming in Python coursera/scripts/3-guess-the-number-0.py | 1,571 | 3.828125 | 4 | #0. import modules
import simpleguitk as simplegui
import random
import math
#1. globals - state
#rules of game - can only guess > 0 & <= 100
num_range = 100
guesses_left = 7
#2. helper fxns to initialize game
def new_game(max_range):
global guesses_left
print "New game. Range is from 0 to ", max_range, "\n"
... |
fcd92d0d4b7ea39942eaecf3edf6fbddf1ae95fa | LounaAkkad/pythonTesting | /BMRBMI.py | 3,487 | 4.125 | 4 | #Louna Akkad 1-5-2018
#this program calculate BMR BMI TDEE
import re
import sys
#validaing the name
while True:
check_name = re.compile('([a-zA-Z])+')
print ('Name should contain At least one character')
name = input('Enter your name: ')
if check_name.match(name):
break
else:
print ('Name should cont... |
9370492e39030976c3da2e5a6454c2633e764efc | snigi-gupta/Algorithms | /Quick_Sort.py | 674 | 3.796875 | 4 | # https://www.geeksforgeeks.org/quick-sort/
class QuickSort:
def partition(self, A, low, high):
pivot = A[high]
i = low - 1
for j in range(low, high):
if A[j] < pivot:
i += 1
A[i], A[j] = A[j], A[i]
A[i+1], A[high] = A[high], A[i+1]
... |
802907eaf6fe935f53dfec5b7a92113784eafea1 | JoshFagan/Code_Wars | /Python/Kyu_7/printer_errors.py | 1,798 | 4.34375 | 4 | #!/usr/bin/python
import sys
def printer_error(sentence):
"""
Return the error rate of the printer.
In a factory a printer prints labels for boxes. For one kind of boxes the
printer has to use colors which, for the sake of simplicity, are named
with letters from a to m.
The colors used b... |
ad9fde3f721de6dfdb430333f163611c520f6611 | infinite-Joy/programming-languages | /python-projects/algo_and_ds/k_closest_points_from_origin.py | 3,444 | 3.578125 | 4 | """
Here we can use quick select to get the values.
time complexity: O(nlogk)
"""
import math
from typing import List
class Solution:
def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
def partition(distances, l, r):
p = r
firsthigh = 0
fo... |
3a8855bfddbec670b554018153cd13adf9b4db61 | chati757/python-learning-space | /pandas/check_in_series.py | 161 | 4.1875 | 4 | import pandas as pd
df = pd.DataFrame({'a':[1,2,3,4],'b':[7,8,8,9]})
print(df['a'].isin(['3']).any())
print(3 in df['a'].values)
print(3 in df['a'].tolist()) |
89ddf7364ab73328f4adae95260c59c497a8fb7c | kalyons11/kevin | /kevin/tests/leet/test_reduce_array_size_half.py | 1,164 | 3.828125 | 4 | """
https://leetcode.com/explore/featured/card/july-leetcoding-challenge-2021/608/week-1-july-1st-july-7th/3804/
"""
from typing import List
from unittest import TestCase
from kevin.leet.reduce_array_size_half import Solution
class TestReduceArraySizeHalf(TestCase):
def _base_test_reduce_array_size_half(self, a... |
8a4a7dc1bb03d5665699df5207f9efd81c3293e6 | DuttaSejuti/Coursera_Python_For_Everybody | /Getting started with python/ex_4_6.py | 1,021 | 4.5 | 4 | #4.6 Write a program to prompt the user for hours and rate per hour using input to
#compute gross pay. Pay should be the normal rate for hours up to 40 and time-and-a-half
#for the hourly rate for all hours worked above 40 hours. Put the logic to do the computation
#of pay in a function called computepay() and use t... |
7ee6ad144a0f52082410ed1801f37154f69cfd88 | elainedo/python_practice | /Array/CarPooling.py | 831 | 3.984375 | 4 | """
There is a car pooling system that picks up and drops off passengers but
every vehicle in this system can only drive in one direction. Each vehicle
has a capacity (empty seats) of passengers.
Given a list of trips where trip[i] = [num_passenger, start, end], return if
you can pick up and drop off passengers at ... |
cf007c2a04be5dc062efd2853921e674b9d567ef | leskin-in/mipt-bioalgo | /hw3/dna_from_k_mers.py | 5,681 | 3.53125 | 4 | #!/usr/bin/env python3
import sys
import copy
def main():
k = None
patterns = []
for l in sys.stdin:
if k is None:
k = int(l[:-1])
continue
patterns.append(l[:-1])
result = reconstruct_dna(patterns)
print(result)
def _check_balancity_and_turn_to_euler_cy... |
ed69a9a7fc6c205a263cc4d9e2c9bf112719084c | yunkaiwang/LeetCodeSol | /dailyChallenge/Mar2021/Mar_28.py | 951 | 3.6875 | 4 | """
Reconstruct Original Digits from English
O(n) solution with O(1) space (at most 26 chars).
Don't like this question, the basic idea is
to identify a unique char for each digit
"""
class Solution:
def originalDigits(self, s: str) -> str:
sMap = collections.Counter(s)
output = ""
digitStr... |
31c09570439c42547b599ce91a4558aee9f56e53 | nie2100/python | /mooc/CalHamletV1.py | 482 | 3.515625 | 4 | # '~!@#$%^&*()_+[]\{}|;:",./<>?'
def getText():
txt = open('hamlet.txt', 'r').read()
txt = txt.lower()
for ch in '~!@#$%^&*()_+[]\{}|;:",./<>?':
txt = txt.replace(ch, '')
return txt
hamleTxt = getText()
words = hamleTxt.split()
counts = {}
for word in words:
counts[word] = counts.get(word,... |
a78bb44ed30a28cdef931fea2873e085d4f93972 | rootid23/fft-py | /dp-top20/subset-sum-problem-dp-25.py | 944 | 3.53125 | 4 |
#Measure the time w/ time python dp-top20/subset-sum-problem-dp-25.py
# Subset Sum Problem | DP-25
# Given a set of non-negative integers, and a value sum, determine if there is a subset of the given
#set with sum equal to given sum.
# Examples: set[] = {3, 34, 4, 12, 5, 2}, sum = 9
# Output: True //There is a sub... |
21216327aa90dfcec4fbc03792271c7a5828e7c7 | iamnavya-agg/Algorithms | /Coursera/algorithms_stanford/Dijkstra/dijkstra.py | 5,513 | 4 | 4 | """
A PriorityQueue implemented with a binary heap with the additional ability to modify a given element
Complexities:
add: O(log(n))
extract_min: O(log(n))
modify_element: O(n + log(n))
re_order_element: O(log(n))
"""
class PriorityQueue:
def __init__(self, elements=None):
self._elements ... |
ab5b0c4bc22ed94ae3eac347306eb557e303f7b3 | nataliabu/proj_euler | /Problem10/problem10.py | 682 | 4.0625 | 4 | import math
primes = [2, 3]
total = 5
def is_prime(number):
square_root = math.floor(math.sqrt(number))
for prime in primes:
# Any number n can have only one primefactor greater than sqrt(n)
if prime <= square_root:
if number % prime == 0:
return False
else... |
fbd93e103ce414b24e0aa04be3d80447aaca06f5 | msbetsy/text_reader | /tests/unittests.py | 2,846 | 3.578125 | 4 | """The module is responsible for unittest."""
import unittest
from text_reader.files import FilesManager
from text_reader.database import SQLDatabase
class UnitTestFilesManager(unittest.TestCase):
"""This class can be used for testing files module.
"""
text_to_test = "me me, our, our, our, our, our, mysel... |
8d532130ed4482209e92f343cb947eafdd639357 | francisrod01/udacity_python_foundations | /03-Use-classes/Turtle-Mini_project/drawing_a_flower.py | 660 | 4.25 | 4 | #!~/envs/udacity-python-env
import turtle
def draw_flower(some_turtle):
for i in range(1, 3):
some_turtle.forward(100)
some_turtle.right(60)
some_turtle.forward(100)
some_turtle.right(120)
def draw_art():
window = turtle.Screen()
window.bgcolor("grey")
# Create the ... |
262721a793ded1e6b942415a3f5b1297b70b2bc9 | pesova/Python_Task2 | /HNGtechs.py | 2,768 | 4.0625 | 4 | from random import choice
from string import ascii_letters
employee_data = []
def main():
question=input("\nNew employee? (Type Y for Yes and N for No): ")
cont=True
while cont:
#convert all strings to uppercase
if question.upper()=="Y":
return Create_password()
... |
004784d9f03d5519f9bffac6da9a161790ab58c6 | stevekutz/dbl_LinkedList_exp | /double_linked_list_2.py | 1,627 | 4.03125 | 4 | class Node:
def __init__(self, data):
self.item = data
self.nref = None
self.pref = None
class DoublyLinkedList:
def __init__(self):
self.start_node = None
def insert_at_start(self, data):
if self.start_node is None:
new_node = Node(data)
s... |
460b008b6d626a35610705ca9df887f4abb984c9 | 0helloword/shiyanlou_python3 | /src/web-server/1.py | 407 | 3.9375 | 4 | #9.self的属性,名称前加上两个下划线,就变成了一个私有变量(private),只有内部可以访问,外部不能访问
class Student2():
def setname(self):
self.name1='jay'
self.__name2='joly'
def getname(self):
print('her name is:',self.name1,self.__name2)
s=Student2()
s.setname()
s.getname()
print(s.name1)
print(s.__name2... |
6dc5c3fecc941dc09b1f9f32472ba8a5c9c9cd85 | Busymeng/MyPython | /Python Data Structure/Ch7-Solutions-Student.py | 1,548 | 3.984375 | 4 | #####################################################################
## Ch7 Quiz
##
"""
1. Secondary memory
2. The handle is a connection to the file's data
3. Whether we want to read data from the file or write data to the file
4. input()
5. It indicates the end of one line of tex... |
6b8b68ba831fa8bd5ec6c44344498b9cdaff17d7 | hardiktaneja/FreshworksAssignment | /FreshWorks_Question_1.py | 2,392 | 3.640625 | 4 |
# coding: utf-8
# In[97]:
# Importing Os - For getting paths in a directory and joining paths
# Importing Json for reading and writing JSON
import os
import json
# In[99]:
# Taking all the Required Inputs
folderPath = input("Enter Folder Path :")
inputFileBaseName = input("Enter Input File Base Name :")
output... |
fb0d98ed9c8005aecd8848b9b3f8470995056226 | xyshun/test-learn | /sortfn.py | 523 | 3.890625 | 4 | # Add a comment line.
def mySort(cmp, *args):
ret = []
for arg in args:
for idx, value in enumerate(ret):
if cmp(arg, value):
ret.insert(idx, arg)
break
else:
ret.append(arg)
return ret
# Define a compare function.
def cmp1(x, y):
... |
b2b58e59caccf7df3da3dae20e6794c7bd5f0ee4 | aixiu/myPythonWork | /pythonABC/猜数字游戏.py | 451 | 3.71875 | 4 | import random
secret = random.randint(1,10)
#print(secret)
print('------猜数字游戏!-----')
guess = 0
while guess != secret:
temp = input('猜数字游戏开始,请输入数字:')
guess = int(temp)
if guess > secret:
print('您输入的数字大了!')
else:
print('您输入的数字小了!')
if guess == secret:
print('恭喜,您猜对了!')
... |
b9fe68dd816c460effcda7464295a596a5790916 | MrChenyyds/uestc_advanced_cv | /proj1/python_code/my_imfilter.py | 3,331 | 3.6875 | 4 | import cv2
import numpy as np
# This function is intended to behave like the built in function imfilter()
# See 'help imfilter' or 'help conv2'. While terms like "filtering" and
# "convolution" might be used interchangeably, and they are indeed nearly
# the same thing, there is a difference:
# from 'help filter2'
# ... |
3da0ceff5e6c66ee2f429399d41f720d1e4f4e48 | amulyadhupad/My-Python-practice | /score.py | 375 | 4.15625 | 4 | """ Code to print the total score of the student """
name=input("Enter the name of the student")
score_list=input("Enter scores of the student")
score_list=[int(x)for x in score_list.split(',')]
def total_score(name,score_list):
total=0
for i in score_list:
total += i
print("Hi " +str(name) + ","+" your ... |
a60ddb26a1fe4ce5d7cccb6dfb83eb6a73d07306 | SugamKhetrapal/HackerRank_Solutions | /10 Days of Statistics/Day 1 - Quartiles.py | 1,893 | 3.78125 | 4 | # Sugam Khetrapal
# import necessary libraries
# import statistics
# take as input n denoting number of elements in the array
n = input()
sum_f = int(n)
# take as input n space-separated integers denoting array elements
integer_list = [int(i) for i in input().split()]
integer_list = sorted(integer_list)
s_list = inte... |
3dfb75ce384f5fcd35a48ee7e34b5328baea1a1f | Banehowl/FebruaryDailyCode2021 | /DailyCode02212021.py | 766 | 4.3125 | 4 | # ----------------------------------------------------------------------
# # Daily Code 02/21/2021
# "Is the Number Less than or Equal to Zero?" Lesson from edabit.com
# Coded by: Banehowl
# ----------------------------------------------------------------------
# Create a function that takes a number as its ... |
bb458311c05bab0934f9e6f5922e71c0944cf1fa | jorti01/Backtracking-Programacion | /Testing/ImplementaciónIF.py | 3,767 | 3.90625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 28 11:11:05 2019
@author: hipatia
"""
# -*- coding: utf-8 -*-
"""
@author: Nicolas Rogers, Diego Herrera y Juan Ortiz
"""
import turtle
from PIL import Image
import random
BLOCK_SIZE = 19
im = Image.open('/home/hipatia/Desktop/maze.jpg')
pixels... |
ccc191d6f4dd0dd2035e489b378ea756455b72e9 | madmax9242/dungeon_game | /treasure_generator.py | 1,755 | 4.125 | 4 | import random
from board_generator import *
treasure = {}
treasure_list = []
# minor_treasure_list = {}
minor_treasure = {}
def treasure_name():
treasure_list = ["The Holy Hand Grenade of Antioch","A SHRUBBERY!","Camelot. It is a silly place.", "A Farm Animal Catapult", "An Insult Spewing Frenchman", "A Large Woode... |
567f623fe444071dbcf64eed503a2b0b687df0c0 | natashatikhonova/IN1000 | /Oblig2/egen_oppgave.py | 1,062 | 3.578125 | 4 | """
Lag et program som selger bussbiletter. Prisene er avhengig av alderen på kjøperen av biletten.
De som er mindre enn 6 aar faar lov aa ta buss gratis.
Barna til og med 12 maa kjope barnebilett for 30 kroner.
Ungdommer til og med 18 maa kjope ungdomsbilett for 40 kroner.
Alle andre maa kjope voksenbilett for 60 kron... |
670d3a50c95f8703aca1734ba14075e15b914f0a | technologyMz/ALL_IN_ML | /yanghui/77combine.py | 1,060 | 3.609375 | 4 |
import copy
class Solution:
def combine(self, n: int, k: int):
input_list = list(range(1, n+1))
combine_list = []
if k > n :
return -1
def backtrack(remain_list, unused_list, k):
if len(unused_list) < k:
return
if k == 0:
... |
f47e18e14f8c4cdd0766f3a572ecf50e5fe6a9e5 | joel-chu/anagram-example | /python/anagram.py | 942 | 3.921875 | 4 | from sys import argv
from mylib.main import WORDS_DIR, jsonData, getWords, getAnagram
def anagram(str):
"""
The main method to get the anagram
"""
l = len(str)
max = jsonData['MAX_CHAR']
min = jsonData['MIN_CHAR']
if l > max or l < min:
print(f"Error: please provide a word between ... |
f2cdcebc743ef793b58e2bda02a3f9b6cc3480a4 | liuyang1/euler | /211.py | 495 | 3.5625 | 4 | from math import sqrt
def getSumSquDiv(n):
if n == 1:
return 1
cnt = 1 + n ** 2
for i in range(2, int(sqrt(n)) + 1):
if n % i == 0:
cnt += i ** 2
v = n / i
if v != i:
cnt += (n / i) ** 2
return cnt
Square = frozenset([i ** 2 for i i... |
a28254f47f247b295b3069e46df9758e43238934 | syurskyi/Algorithms_and_Data_Structure | /_algorithms_challenges/w3resource/Practice_python-master/python_if_loops.py | 6,183 | 3.84375 | 4 | import random
import sys
import re
# from python_lists import (make_list, make_list_num, make_str_list,
# make_num_str_list)
def dev7_multiply5():
""" 1: returns all numbers in range between 1500 and 2700
which are divisible by 5 and 7.
"""
answer_list = []
for number in ... |
af74b8d3a5066a7bb72598a849e1e31ca20cc533 | MarsBighead/mustang | /Python/hackerrank/alternating-characters.py | 415 | 3.828125 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the alternatingCharacters function below.
def alternatingCharacters(s):
cursor=s[0]
#print(cursor)
cnt=0
for char in s[1:]:
if char==cursor:
cnt+=1
else:
cursor=char
return cn... |
a2034bf3d232ee8b0006bc593dfaa5e247c5cb35 | Stormzudi/Python3 | /course_9_2.py | 1,285 | 4.15625 | 4 | # -*- coding: utf-8 -*-
# @Time : 2020/3/11 15:53
# @Author : ZhuNian
# @FileName: course_9_2.py
# @Software: PyCharm
class Student():
def __init__(self,name,age):
self.name = name
self.age = age
student = Student('老朱',18)
print(student.name)
print(student.__dict__) #返回student 中具体的 变量值
pr... |
aeb1e65ff790503d7b53b5f503da0ef814b0e267 | evaristrust/Courses-Learning | /SecondProgram/pytbasics/CHALLENGES/Edabit/guessNumb.py | 736 | 4.15625 | 4 | # We are going to test something
# play the game of choosing higher or lower
# initialize variables max_number, guess, trials, random_number
import random
max_number = 20
guess = 0
trials = 1
random_number = random.randint(1, max_number)
print('Choose a number between 1 and 20: ')
while guess != random_number:
gue... |
3bfb3266e9a74f3234ad18a80b56d2fc9fca3368 | lemejiamo/holbertonschool-higher_level_programming | /0x0A-python-inheritance/9-rectangle.py | 790 | 4.03125 | 4 | #!/usr/bin/python3
""" class to learn python project 0x0A Holberton School """
BaseGeometry = __import__('7-base_geometry').BaseGeometry
class Rectangle(BaseGeometry):
""" define a class Rectangle inherits from BaseGeometry"""
def __init__(self, width, height):
""" constructor
Attributes:
... |
bcda46ca932699ac4cdc748b387ec3b9967eab55 | dcHHH/UnderstandingComputation | /the_meaning_of_programs/big-step.py | 4,230 | 3.90625 | 4 | class Number:
def __init__(self, value):
self.value = value
def __repr__(self):
return f"{self.value}"
def evaluate(self, environment):
return self
class Boolean:
def __init__(self, value):
self.value = value
def __repr__(self):
return f"{self.value}"
... |
fffa1d55a995c20a9cc5d7fc07bbc4f5282369a6 | LYSHN/python-100-day | /day-025/datetime&time.py | 1,463 | 4.09375 | 4 | #!/usr/bin/python3
#时间戳
import time
print ("当前时间戳为:", time.time())
#函数执行的间隔时间
import time
def calculateTime():
item = 1
for i in range(1,100000):
item = item + i
return item
startTime = time.time()
result = calculateTime()
endTime = time.time()
print('计算结果:'+ str(result))
print('执... |
d5e97bb9f263a908bc2fe2b798fde0ace680d67e | ypmoraes/Curso_em_video | /ex053.py | 1,097 | 4.21875 | 4 | '''
########################################################################################
## Enunciado: Crie um programa que leia uma frase qualquer e diga ##
## se ela eh um palindromo, desconsiderando os espacos ##
## ... |
bd407674e9a3973191db493bffa7999ee7541303 | wandabwa2004/sentiment_analysis | /gr_sentiment_analysis/gr_features.py | 11,649 | 3.84375 | 4 | import pandas as pd
import numpy as np
import string
import sqlite3
import matplotlib.pyplot as plt
import seaborn as sns
import os
import sqlite3
def words_to_list(str):
"""separate out space separated words from input string. Strip all control characters and punctioation except ' and -.
Change each word to ... |
a1ef83930e8606b82957dca76d27c4e5b6f8b6aa | dos09/PythonTest | /reference_code/reusable_code/datetime_/string_to_UTC_datetime.py | 739 | 3.890625 | 4 | from datetime import timezone
from dateutil.parser import parse as dateutil_parse
def string_to_utc_date_or_none(str_date):
d = None
try:
d = dateutil_parse(str_date)
except Exception:
return None
return datetime_to_utc_or_none(d)
def datetime_to_utc_or_none(_date):
# for aware... |
77f2728dde25eb926b66946492970deecabe4ac7 | WillHTam/pytorch-reference | /torch_loss_andoptimizers.py | 2,250 | 3.53125 | 4 | """
Loss functions are implemented as an nn.Module subclass
Usually accpets two arguments: output(prediction) and desired output(labels)
Most common are
nn.MSELoss for mse
nn.BCELoss for binary cross-entropy loss
This is for single probability value ie usually Sigmoid layer output
nn.BCEWithLogit... |
97caf7b7f9c8cf5e7ddc944f925320a7f8c785f7 | mparkcode/codingbat_python_solutions | /string_2.py | 1,598 | 3.84375 | 4 | 1
def double_char(str):
newStr = ""
for i in range(len(str)):
newStr += str[i]*2
return newStr
print(double_char('The'))
print(double_char('AAbb'))
print(double_char('Hi-There'))
2
def count_hi(str):
count = 0
for i in range(len(str)-1):
if str[i]+str[i+1] == 'hi':
... |
9c77d73d656da5876c05b247666abeb1f09d904d | HATIMj/MyPythonProblems | /Palindrome-2.py | 960 | 4.03125 | 4 | # PALINDROME PART 2
def pal(n):
"""Function which gives out the next palindrome"""
n+=1 #initializing...
while not ispal(n):
n+=1 #if not palindrome then returns next value until we get a palindrome
return n
def... |
0f684176fd5495828e19074b426bdb76dbfa011a | Gayatri1001/python_basics | /9.file_io.py | 649 | 4.40625 | 4 | # File Writing
file_obj = open("my_file.txt", "w")
content = """
these are my file contents
this is line #2
this is line #3
bla bla bla
"""
file_obj.write(content)
file_obj.close()
# File Reading
file_obj = open("my_file.txt", "r")
my_data = file_obj.read()
print(f'file contents: {my_data}')
file_obj.close()
# anothe... |
ea3ccecdfe7f2daf88fcbedbdd246e4def0eb02c | zero1hac/cp-practice | /codeforces/141A.py | 343 | 3.59375 | 4 | line1 = raw_input().strip()
line2 = raw_input().strip()
line3 = raw_input().strip()
line3 = ''.join(sorted(line3))
flag = 0
total = line1+line2
total = ''.join(sorted(total))
if len(total)!=len(line3):
flag=1
print "NO"
else:
for i in range(len(total)):
if total[i] != line3[i]:
print "NO"
flag=1
break
if... |
bd37ee1fcfb29d7c8bbaf46e60bd9f93177b0cb5 | sfujiwara/ProjectEuler | /Python/problem004.py | 635 | 3.828125 | 4 | # -*- coding: utf-8 -*-
# nが回文数か調べる関数
# mod 10 で調べるより, 文字列で反転させた方がちょっと速い
def is_palindrome(n):
return str(n) == str(n)[::-1]
def is_palindrome2(n):
m = n
reversed = 0
while n > 0:
reversed = 10 * reversed + n % 10
n = n / 10
return reversed == m
if __name__ == '__main__':
an... |
e2b20397f0d3d92ca1818f1c542d27acb0fbac61 | hosmanadam/coding-challenges | /@Project Euler/006_sum-square-difference/sum-square-difference.py | 335 | 3.53125 | 4 | """https://projecteuler.net/problem=6"""
"""v2"""
print(sum(range(1,101))**2 - sum({n**2 for n in range(1, 101)}))
"""v1 - Verbose"""
# sum_of_squares = sum({n**2 for n in range(1, 101)})
# square_of_sums = sum(range(1,101))**2
# print(f"Difference between {sum_of_squares} and {square_of_sums} is {square_of_sums-sum_... |
996094e1a75e8369c58f0caa417f58882b9c7285 | aizhansapina/BFDjango | /week1/informatics/For loop/CFj.py | 75 | 3.515625 | 4 | sum = 0
for num in range(1, 101):
a = int(input())
sum += a
print(sum)
|
ac0cc0a34411c35a499e63564dd4445ce6ee2917 | nsnider7/CSE331Repo | /Project5/AVLTree.py | 16,432 | 3.765625 | 4 | import random as r
class Node:
# DO NOT MODIFY THIS CLASS #
__slots__ = 'value', 'parent', 'left', 'right', 'height'
def __init__(self, value, parent=None, left=None, right=None):
"""
Initialization of a node
:param value: value stored at the node
:param parent: the parent... |
09341d8de2d2213895e71943f30040631bcd6056 | esix/competitive-programming | /acmp/~contest-40495/A/main.py | 204 | 3.796875 | 4 | idx = {
"rock": 0,
"scissors": 1,
"paper": 2
}
a, b = input(), input()
a = idx[a]
b = idx[b]
if b == (a + 1) % 3:
print("first")
elif a == (b+1)%3:
print("second")
else:
print("draw")
|
d1dd0ea52a75054eb7388d2e39271559dfe320d7 | armand-jr/Sonkrag | /code/algorithms/genetic_pop_hc.py | 9,353 | 3.515625 | 4 | ####################################################################################################################
#
# genetic.py from SONKRAG
# Armand Stiens, Willem Folkers, Dionne Ruigrok
#
# Minor Programmeren UvA 2021
#
# - Makes n random solution and tries to improve with the genetic population hillcli... |
3e16784f7465a6a5a697ff586d6d3666124a5aa7 | odia101/Class5 | /generic_parser.py | 2,327 | 3.8125 | 4 | #!/usr/bin/env python
from argparse import ArgumentParser
parser = ArgumentParser(description='A CSV reader + stats makes')
parser.add_argument('csvfile', help ='path to the input of csv file')
parsed_args = parser.parse_args()
print(parsed_args)
print(parsed_args.csvfile)
my_csv_file = parsed_args.csvfile
import... |
baa7d7dee61ba9724ab281298e478abb981cba82 | xshen1122/Follow_Huang_Python | /test18.py | 850 | 3.90625 | 4 | # test18.py
# coding: utf-8
'''
这个练习里面搞清楚类和对象
'''
class Animal(object):
pass
class Dog(Animal):
def __init__(self,name):
self.name = name
class Cat(Animal):
def __init__(self,name):
self.name = name
class Person(Animal):
def __init__(self,name):
self.name = name
self.pet = None #人有一个宠物, pet是个类,是个对象,... |
835eef2ba98f183778fbf5a8a5da546d87e28fa0 | KharismaSatrio/-Digit | /Digit.py | 1,048 | 3.921875 | 4 | #Soal_3
def digitAwal(a,b): #fungsi digunakan untuk mengambil nilai paling awal
c=a**b #operasi matematika a pangkat b yang di masukan ke variabel c
cc = (str(c))[0] #disini variabel c dijadikan string, dan digunakan fungsi slice untuk mengambil variabel paling awal dan di assign ke variabel baru
return... |
560bcb18a4bd2e4efc715a54962632d34f3e728a | Artemosypchuk/stuff | /pattern.py | 1,077 | 3.65625 | 4 | if __name__ == "__main__":
pass
class Object:
def __init__(self, name: str, surname: str, age: int, skill: str):
self.__name: str = name
self.__surname: str = surname
self.__age: int = age
self.__skill = skill
@property
def name(self):
return self.__name
@... |
addc4a14c6cf2eae2bbf695b0d60bf6b9c5b28cb | c0D3M/Optimization_Problems | /NP/GraphColor.py | 1,752 | 3.78125 | 4 | # python3
import itertools
import os
''' Graph Coloring Problem using 3-color
Input: Undirected Graph
Output: Assignment of 3-color to various nodes
'''
clauses = []
def exactly_one_of(literals):
# Adds one of literals to be true
clauses.append([l for l in literals])
# This add 2 negated literals to clause... |
a0492cb79e724f79f461be6fdb80308007cea2e2 | datadavis2/hackerrank | /python/second_highest.py | 363 | 4.03125 | 4 | '''
Given the participants' score sheet for your University Sports Day, you are required to find the runner-up
score. You are given n scores. Store them in a list and find the score of the runner-up.
'''
n = int(input())
arr = list(map(int, input().split()))
maxval = (max(arr))
arr2 = []
for i in arr:
if i != maxv... |
793fd145bae35c5f680bb85013a4b2f2777855e7 | rhenderson2/python1-class | /chapter05/hw_5-12_5-13_EC.py | 459 | 3.828125 | 4 | # homework assignment section 5-12, 5-13 / EC
# Reviewed coding a lot during course of assignments.
# Doing Extra Credit from email in lieu of 5-13 below.
print("*** Prime numbers from 1 - 100. ***\n")
temporary_list = []
current_number = 1
key = 1
while current_number < 100:
current_number += 1
if current_num... |
f7faff8227b9c57d342fabf0fd08a39a1b4bec92 | luoshanya/crawl_project | /数据分析-NumPy科学计算/NumPy_test01.py | 854 | 3.84375 | 4 | import numpy as np
import matplotlib.pyplot as plt
#设置随机数
# random_data = np.random.rand(2,3)
# print(random_data)
# print(random_data*10)
#返回源随机数头(2,3) 与上面相同
# print(random_data.shape)
#返回浮点数
# print(random_data.dtype)
#快速创建数组 numpy.ndarray 类型
# data = [2,4,6,7,8]
#
# data_ndarray = np.array(data)
# print(type(d... |
8d3e6e8f4384b5c2a7ce87b0617c1c3ec8cef864 | Pramod-Shrinivas/Project-Euler | /Python/015-1.py | 796 | 3.828125 | 4 | #!/usr/bin/python
'''
Purpose: https://projecteuler.net/problem=15
@author:Pramod S
Straight forward combinatorics approach
In a 2x2 grid the number of paths needed to reach bottom right from top left is 4(doesnt matter how
you take right or down). In other words out of 4 paths i have to choose 2 i.... |
801a45fdd15cdd76260028eb9ceed252f3935b9d | kamojiro/atcoderall | /regular/110/A.py | 216 | 3.5625 | 4 | #import sys
#input = sys.stdin.readline
from math import gcd
def main():
N = int( input())
n = 2
for k in range(2,N+1):
n = n*k//gcd(n,k)
print(n+1)
if __name__ == '__main__':
main()
|
83a1021018b6aa2ca31c13026877b7ceb9a75eb2 | MihaiCatescu/python_exercises | /exercise6.py | 528 | 4.15625 | 4 | '''
Let’s say I give you a list saved in a variable: a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]. Write a function
that takes this list and makes a new list that has only the even elements of this list in it.
'''
a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
b = []
def create_even_list():
for number in a:
... |
591bf968803ea7bf47f4879cee408d4910bbb62b | Jayesh97/programmming | /numbers/150_ReverseNailPolish.py | 814 | 3.953125 | 4 | tokens = ["10","6","9","3","+","-11","*","/","*","17","+","5","+"]
def stackify(tokens):
stack = []
for i in tokens:
if i == "+" or i=="-" or i=="*" or i=="/":
num2 = stack.pop()
num1 = stack.pop()
sign = i
result = evaluate(int(num1),int(num2),sign)
... |
57507a74416da677237ff2e36fee9a39d86e3adf | kglueck/xlaprs | /units.py | 2,057 | 3.625 | 4 | #!/usr/bin/python
#meters & feet
def m2f(m): return m * 3.28083989501
def f2m(ft): return ft * 0.3048
#yard = 0.9144meters, exactly, by definition. ft = 1/3 yard
#miles and kilometers
def mi2km(mi): return mi * 1.609344
def km2mi(km): return km * .621371192237
#nautical miles and miles
def mi2nm(mi): re... |
787a48a593cac653f90fb1eb54783ffece7855fb | keinam53/Python_Poczatek | /Wbudowane_struktury_danych/6_mutable_immutable/przyklad_1.py | 1,456 | 3.84375 | 4 | def run():
shopping_list = ["woda", "chleb", "mąka"]
my_list = shopping_list
your_list = shopping_list
print("Lista zakupów:", shopping_list)
print("Moja lista: ", my_list)
print("Twoja lista: ", your_list)
print(id(shopping_list))
print(id(my_list))
print(id(your_list))
print... |
b10e53fd77600650e32a2b93935870fcbc58ac92 | Saksham1997/leetrank_practice | /leetcode_Decompress_Run_length_encoded_list.py | 354 | 3.71875 | 4 | def decompressRLElist(nums):
lis=[]
i=0
while i in range(len(nums)-1):
freq=nums[i]
val=nums[i+1]
i+=2
print("freq and val is {} {}".format(freq,val))
for j in range(freq):
lis.append(val)
print("list now is {}".format(lis))
return lis
pr... |
19accdbc94d04b63afe7b4ffabf9e81b81176183 | kaixiang1212/kNN-Implementation | /nnClass.py | 6,233 | 3.765625 | 4 | import numpy as np
import pandas as pd
import math
# import matplotlib.pyplot as plt
# knn classifier
class knnClassifier:
def __init__(self, train, labels, k , dis_mode = 'e', pred_mode = 'vote'):
self.trainSet = train # train set
self.labels = np.array(labels) # labels
self.featureSize = len(tr... |
63762c218bfa1b72319b538f4e9ac73c3a326895 | eselyavka/python | /leetcode/solution_1544.py | 832 | 3.609375 | 4 | #!/usr/bin/env python
import unittest
class Solution(object):
def makeGood(self, s):
"""
:type s: str
:rtype: str
"""
if not s or len(s) == 1:
return s
arr, i = list(s), 1
while i < len(arr):
if arr[i].lower() == arr[i-1].lower():
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.