blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
371272def74700f4b43de365e35cb961abe73b1c | InYourFuture/tree | /tree.py | 2,858 | 4.15625 | 4 | # 循环实现二叉树的前序遍历
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution1:
def preorderraversal(self, root):
ret, stack = [], [root]
while stack:
node = stack.pop()
... |
05693952d0b591e481cfe5413f2f7024b745c746 | billwangcn/MyPython | /sodoku/sudoku02.py | 1,501 | 4.09375 | 4 | #! /usr/bin/env python
# coding:utf-8
# 判断输入的九宫格的格数是否为奇数
def if_odd(n):
if n % 2 == 1:
return True
else:
return False
# 九宫格填写数的法则
"""
按照下面的方式排列
-------------->x(从1到n)
|
|
|y方向(从1到n)
1、第一个数放在X方向的中间位置
2、其它数顺次放置各个位置,并依据如下原则:(假设第一个数是a,第二个数是b)
以a为中心的位置关系分别为:
左上|上|右上
左 |a |右
左下|下|右下
(1)b放在a的右上位... |
f6476856ea595f15b677549bef3bbf3320116a4c | billwangcn/MyPython | /algorithm/int_divide.py | 461 | 3.515625 | 4 | #! /usr/bin/env python
# encoding:utf-8
"""
将一个整数,分拆为若干整数的和。例如实现:
4=3+1
4=2+2
4=2+1+1
4=1+1+1+1
"""
def divide(m, r, out):
if (r == 0):
return True
m1 = r
while m1 > 0:
if (m1 <= m):
out.append(m1)
if (divide(m1, r - m1, out)):
print
... |
e5f98564edf02958ff5be9d3915fbc9d18f9c1d9 | breecoffey/Machine-Learning | /Homework2part2.py | 3,506 | 3.859375 | 4 | class AdalineGD(object):
"""ADAptive LInear NEuron classifier.
Parameters
------------
eta : float
Learning rate (between 0.0 and 1.0)
n_iter : int
Passes over the training dataset.
Attributes
-----------
w_ : 1d-array
Weights after fitting.
cost_ : list
... |
bfe427c331a3d1982b2aa13cf45707e063356568 | mwpnava/Python-Code | /My_own_Python_package/guesser_game/numberGuesserGame.py | 2,373 | 4.28125 | 4 | from random import randrange
from .GuesserGame import Guesser
class GuessMyNumber(Guesser):
""" GuessMyNumber class for calculating the result of arithmetic operations applied to an unknow number
given by the player
Attributes:
numberinMind represents the number a player has in mind at the end o... |
4e97f7e8c80fedb802649a3e1c51c60800a15bee | mwpnava/Python-Code | /missingValue3.py | 453 | 4.25 | 4 | '''
Consider an array of non-negative integers.
A second array is formed by shuffling the elements of the first array and
deleting a random element. Given these two arrays, find which element is missing in the second array.
Approach 3
'''
def missingValue(arr1,arr2):
arr1.sort()
arr2.sort()
for n1,n2 in... |
05f62b6c58e5b56bbcd2a09007aab7c536e1142b | a-benno/randomizer-cli-tool | /randomize/randomizer.py | 2,205 | 4.15625 | 4 | """
########################################################################################################################
## ##
## Copyright (C) 2021 Adjust GmbH. All rights r... |
0cc30abd316e8d853a5b0f1a57a682c3ce8191f7 | dkraytsberg/pysql | /pysql.py | 1,347 | 3.53125 | 4 | import mysql
from mysql.connector import errorcode
def make_db_params():
"""
returns a map with some default connection parameters.
full list found at
https://dev.mysql.com/doc/connector-python/en/connector-python-connectargs.html
"""
user = raw_input("enter user: ")
password = raw_input("enter password: ")
h... |
9aa816f2ec3ce6578647b7c705b9ff26e8f3860e | x78325/python | /intro.py | 316 | 3.78125 | 4 | import math
def area():
a=0
while a==0 :
try:
r=input('输入园的半径: ')
area=int(r)**2*math.pi
a=1
except:
print('请输入整数作为半径!')
print('园的面积等于{:.2f}'.format(area))
if __name__=='__main__':
area()
|
1716e950530a161a3fedb8d5ef8c10a9ff306601 | alexzhukovwork/GraphicEditor | /app/primitives/pen.py | 802 | 3.59375 | 4 | from primitives.primitive import Primitive
class Pen(Primitive):
def __init__(self, position, color, qPen, qBrush=None):
Primitive.__init__(self, position, -1, color, qPen, qBrush)
self.pixels = []
def draw(self, canvas, alpha):
Primitive.draw(self, canvas, alpha)
len = self.... |
a5e874b8512dbf070aa0f3cc4f0e9ae20aff1dde | kpdzhnv/SQL-Injection-Python-SQLite | /3.py | 1,443 | 3.921875 | 4 | import sqlite3
from sqlite3 import Error
def create_connection(db_file):
""" create a database connection to the SQLite database
specified by db_file
:param db_file: database file
:return: Connection object or None
"""
conn = None
try:
conn = sqlite3.connect(db_file)
except... |
8a566516e486ba6ccbfa9797edf01b724732f619 | colinrdavidson/Machine-Learning-with-Python | /regression/read_csv.py | 753 | 3.890625 | 4 | import csv
import numpy as np
'''
read_csv(file) where file is a string.
file is the path to the csv file.
It is assumed that there is a single y vector(for now).
X and y are returned as numpy matrices with float entries.
'''
def read_csv(file):
print("Reading in data from", file, ".")
raw_data =... |
9de395496947ba004e30c6afe851d6b176bccfd4 | bflynn14/school | /511/homework/blackjack.py | 1,201 | 3.59375 | 4 | import random
from collections import defaultdict
class Blackjack(object):
'''
'''
Cards = [5,10,11]
def hit(self, hand, dirty=0):
'''
'''
if dirty > random.random():
total = sum(hand)
worst = [(total + c, c) for c in self.Cards]
for t, c in ... |
0dbbf75efedd73f737580f59926cf7afd5b88912 | bflynn14/school | /544/cakery/utilities.py | 5,300 | 4.0625 | 4 | from itertools import chain, combinations
def powerset(iterable):
''' Given an iterable, create the powerset
:params iterable: The iterable to create a powerset of
:returns: A powerset iterator
'''
s = list(iterable)
return chain.from_iterable(combinations(s, r) for r in range(1, len(s) + 1))... |
46e43ab4f029967a87dc01d79ab52bc153f8af6a | tskiranmayee/Data-Structures | /Search/LinearSearch.py | 167 | 3.640625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon May 10 19:53:21 2021
@author: tskir
"""
""" Linear Search-Easy way"""
a=[4,3,5,2,6]
q=a.index(5)
print("Index of 5 is:",q) |
f1c4da602d586e2df80e5552da8ab2c2eb122bb6 | themiurge/machine_learning_examples3 | /linear_regression_class/my/lr_1d.py | 565 | 3.65625 | 4 | import numpy as np
import matplotlib.pyplot as plt
import lr
# load the data
X = []
Y = []
for line in open('../data_1d.csv'):
x, y = line.split(',')
X.append(float(x))
Y.append(float(y))
# convert to numpy arrays
X = np.array(X)
Y = np.array(Y)
# compute linear regression coefficients
a, b = lr.linreg(X... |
86ab00b1075ba0b751ecf2f6a5b2312c870fafc1 | sonishrey9/Movie-Recommendation-Engine | /game.py | 2,569 | 3.546875 | 4 | # To add a new cell, type '# %%'
# To add a new markdown cell, type '# %% [markdown]'
# %%
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
# %%
game = pd.read_csv("game.csv")
game
# %%
game.isna().sum()
# %% [markdown]
# ## No Missing Files
# %%
# Creating a Tfidf Vectorizer to re... |
f6b0c128d80f29cc493e2f2901969d79a1e2e0e6 | theyusko/tsp-heuristics | /algo/greedy.py | 478 | 3.75 | 4 | import numpy as np
# Step 1. Look at all the arcs with min distance
# Step 2. Choose the n cheapest arcs
# Step 3. List the distance of arcs starting from the min distance to max distance
# Step 4. Draw and check if it forms a hamiltonian cycle
# Step 5. If step 4 forms a Hamiltonian cycle then we have an optimal sol... |
62c4b5f4848020e8433095fed69dc064f8a1ae6b | codematician/study | /study/utils.py | 495 | 3.546875 | 4 | """Some utilities for machine learning algorithms"""
from math import log2
def majority_val(df, attr):
"""Gives the majority value of column attr in dataframe df"""
if len(df) == 0:
return None
mode = df[attr].mode()
return mode[0] if len(mode) > 0 else df[attr].iloc[0]
def series_info(serie... |
37d169852b3eaa139e5f80d5e9e3253025ba1873 | WilliamRayJohnson/UniProjectArchive | /courses/cs325/assignment2/Bioinfo_Assignment2b_Johnson_Reddy_Wilson.py | 14,153 | 3.75 | 4 | '''
CS 325 Intro to Bioinformatics
Assignment 2
William Ray Johnson
Sankeerth Reddy
Kelsey Wilson
Last Edited: 14 November 2016
runtime around 20 minutes
'''
import sys
from readfasta import *
from itertools import combinations
from random import randint
from statistics import mean
'''
Finds the optimal local alignm... |
abc460b5992af82b25f36b02c9b53c5fee1b7a2a | WilliamRayJohnson/UniProjectArchive | /courses/cs325/midterm/Johnson_CS_MidtermQ4.py | 5,972 | 3.921875 | 4 | '''
CS 325 Intro to Bioinformatics Fall 2016 Midterm: CS Version
Question #4: Muti-string alignment
William Ray Johnson
Last Edited: 23 October 2016
'''
import sys
from readfasta import *
from itertools import combinations
'''
Finds the optimal alignment by calculating a memo using dynamic programming.
row: the row c... |
7dc988b02350b88e2674437226ec67c0571e9d98 | bagelboy/adventofcode | /2015/day01/santa_elevator.py | 898 | 4.0625 | 4 | #!/usr/bin/env python3
def follow_directions(directions):
floor = 0
basement_position = 0
for position, direction in enumerate(directions, start=1):
if direction == '(':
floor += 1
elif direction == ')':
floor -= 1
if floor < 0 and basement_position == 0:
... |
b370f880a0b24a7c0ac361744019408c56fb6c7f | bagelboy/adventofcode | /2017/day12/graph.py | 914 | 3.75 | 4 | def read_input():
connections = []
with open('input') as input:
for line in input:
values = line.rstrip().split(' <-> ', 2)
other_nodes = values[1].split(', ')
connections.append([int(x) for x in other_nodes])
return connections
neighbors = read_input()
def di... |
f4ad9050c3aef51ed4d6cf03219f1210cec7a9a1 | vzqz2186/DAnA_Scripts | /Maze/v3/vazquez_maze_v3.03.py | 8,947 | 4.21875 | 4 | """
Program: vazquez_maze_v3.03.py
Author: Daniel Vazquez
Date: 03/17/2018 (v1.00: DOES NOT WORK)
03/19/2018 (v1.01: DOES NOT WORK)
03/20/2018 (v1.02, v1.03: DO NOT WORK)
03/22/2018 (v2.00, v2.01: DO NOT WORK)
03... |
8362df19e83ad9aa361557272d9abed226133853 | vzqz2186/DAnA_Scripts | /Arrays.Lists/vazquez_hw021218_v1.00.py | 2,015 | 4.15625 | 4 | """
Program: Arrays/List
Author: Daniel Vazquez
Date: 02/10/2018
Assignment: Create array/list with 20 possible elements. Fill with 10
random integers 1 <= n <= 100. Write a function to insert value
in middle of list.
Due Date:
Objective: Write a function to insert value in... |
579e18c1a1fbf0aa6c3f405afe1033bce344981f | vzqz2186/DAnA_Scripts | /Maze/v3/vazquez_maze_v3.00.py | 1,006 | 3.734375 | 4 | from random import randint
def main():
height = 5
width = 5
grid = []
for i in range(height):
grid.append([])
for j in range(width):
grid[i].append(2)
grid[0][0] = 0
generate(grid, i, j, height, width)
for i in range(len(grid)):
pri... |
950737cb22b6aec643d62fe81cbb7ef6c446fb20 | frostming/ShowMeTheCode | /q4/count_words.py | 532 | 4.28125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# 第 0004 题:任一个英文的纯文本文件,统计其中的单词出现的个数。
# @Author: Frost Ming
# @Email: mianghong@gmail.com
# @Date: 2016/3/6
import re
def count_words(file):
pattern = re.compile(r'\b[a-zA-Z\']+\b')
target = open(file, 'r').read()
res = pattern.findall(target)
print res
... |
50d30ff54aa16bc849fdbbe45278b6935216c352 | jdobner/grok-code | /2D_water_trap.py | 325 | 3.53125 | 4 | from collections import namedtuple
from typing import List
class Solution:
def trapRainWater(self, height_map: List[List[int]]) -> int:
Heights = namedtuple('Heights', ['H', 'N', 'S', 'E', 'W'])
dummy = Heights()
effectiveHeights: List[List[Heights]] = []
prev = dummy
for (... |
b7757a06f89cacb51cb96eba0c685b4cf31a9b4a | jdobner/grok-code | /find_smallest_sub2.py | 1,537 | 4.21875 | 4 | def find_substring(str, pattern):
""" Given a string and a pattern, find the smallest substring in
the given string which has all the characters of the given pattern.
:param str:
:param pattern:
:return: str
>>> find_substring("aabdec", 'abc')
'abdec'
>>> find_substring("abdbca", 'abc')
'bca'
>>> f... |
3fc4991efeacc6d64e11c497d941f735ad0c6977 | jdobner/grok-code | /TripletSumtoZero.py | 4,436 | 4.25 | 4 | from typing import List
def pair_with_targetsum(arr, target_sum, ignore):
"""
Given an array of sorted numbers and a target sum, find a pair in the array whose
sum is equal to the given target.
:param arr:
:param target_sum:
:return:
>>> pair_with_targetsum(arr=[1, 2, 3, 4, 6], target_sum... |
2f395977cda37422b8b98e1a39ea7503ddaa4ac9 | jdobner/grok-code | /remove_dups.py | 832 | 3.984375 | 4 | def remove_duplicates(arr):
"""
Given an array of sorted numbers, remove all duplicates from it.
You should not use any extra space; after removing the duplicates in-place return
the length of the subarray that has no duplicate in it.
:param arr:
:return:
>>> a = [2, 3, 3, 3, 6, 9, 9]; rem... |
eacaa02210dc10ac23c699c11ec8ff6e42201170 | SriganeshNk/Workouts | /qsort.py | 960 | 3.625 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
def partition(a):
n = len(a)
last = n-2
first = 0
pivot = n-1
while first < last:
while a[last] > a[pivot] and last >= 0:
last -= 1
while a[first] < a[pivot] and first < pivot:
fir... |
1590fc9292df1e400e66519b70272ba9a5c4c089 | vbelousPy/py_lessons | /lesson_16/slave.py | 193 | 3.625 | 4 | import sys
arguments = sys.argv
start = int(arguments[1])
stop = int(arguments[2])
length = int(arguments[3]) + 1
result = 0
for i in range(start, stop, length):
result += i
print(result)
|
4f50df77c26e6bc959ace7487656078d672b920a | SeanXiaohengMao/Leetcode | /Mao/760.py | 491 | 3.609375 | 4 | class Solution(object):
def anagramMappings(self, A, B):
"""
:type A: List[int]
:type B: List[int]
:rtype: List[int]
"""
dic = {}
li = []
for i, num in enumerate(B):
if num in dic:
dic[num].append(i)
else:
dic[num]... |
ff257c003b0e8ff8514598086821a2d255526eb7 | SeanXiaohengMao/Leetcode | /Mao/234.py | 748 | 3.71875 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def isPalindrome(self, head):
"""
:type head: ListNode
:rtype: bool
"""
slow = fast = head
while fast... |
4b89963de968a7e2c4f821660f2d55a254836cca | gheritarish/paylead-cinema | /utils/get_data.py | 1,997 | 3.84375 | 4 | import re
from typing import List
import requests
from bs4 import BeautifulSoup
def get_url_from_site(site_url: str) -> List[str]:
"""Function to get all URL from a given website, without any filtering.
Args:
site_url (str): The site URL from which to scrap the data.
Returns:
List[str]:... |
02c484b6cb30a7187b1b67585dfb0158747db857 | jamestonkin/file_storage | /car_storage.py | 1,195 | 4.34375 | 4 | class Car_storage:
""" This adds functionality and stores car list makes and models"""
def __init__(self):
self.car_makes = list()
self.car_models = list()
def read_car_makes(self):
""" Reads car makes from car-makes.txt file """
with open('car-makes.txt', 'r') as makes:
... |
3db76b914c94a505a8de35fa2621e3b70e38cec1 | wraighta/python_practice | /13_Fibonacci.py | 215 | 3.9375 | 4 | #13 Fibonacci
i = raw_input("The nth fibonacci: ")
i = int(i)
print i
def fib(n):
j=0
n,m=1,1
for j in range(n-1):
n,m = m, n+m
print n
print m
return n
print fib(i)
|
141aa4dc2cef1ce5d28b290266dff257479806fa | lweibel/CodeTeam | /Competition 3/task_for_alexey.py | 1,056 | 3.953125 | 4 | def lcm(a, b):
# finds the least common multiple
return a*b // gcd(a, b)
def gcd(a, b):
# finds the greatest common divisor
if a == 0: return b
return gcd(b % a, a)
T = int(input())
# loop through each test case
for t in range(T):
N = int(input())
# store integers separated by a space as a... |
f14df2414e1d8cc51864188af1fe9d17071fd638 | sennhvi/rbpi_python | /chapter2-cat-rat.py | 1,542 | 3.9375 | 4 | import turtle
import time
box_size = 200
caught = False
score = 0
# functions that are called on key presses
def up():
mouse.forward(10)
check_bound()
def left():
mouse.left(45)
def right():
mouse.right(45)
def back():
mouse.backward(10)
check_bound()
def quit_turtles():
window.by... |
febdf1ea7d39be0fd144488b75c2f145d07a5677 | iumentum666/PythonCrashCourse | /Kapittel 10 - 11/word_count.py | 894 | 4.46875 | 4 |
# This is a test of files that are not found. If the file is not present,
# This will throw an error. We need to handle that error.
# In the previous file, we had an error. Here we will create the file
# In this version we will work with several files
# So the bulk of the code is put in a function
def count_words(fi... |
b888c1112be2bc339c8af821aded0817192b8884 | theakholic/udacity-cs101 | /lesson2/enigma.py | 3,873 | 3.890625 | 4 | #-------------------------------------------------------------------------------
# Name: enigma.py
# Purpose: simulate 3 rotor enigma
#
#
# Author: Akshay
#
# Created: 14-05-2015
#-------------------------------------------------------------------------------
def interleave(l1, l2):
"""
Int... |
20416741df424e96a4d6969208c9e8f695fac684 | theakholic/udacity-cs101 | /recursion.py | 4,838 | 3.6875 | 4 | #-------------------------------------------------------------------------------
# Name: recursion.py
# Purpose:
#
# Author: Akshay
#
# Created: 18-05-2015
# Copyright: (c) Akshay 2015
# Licence: <your licence>
#-------------------------------------------------------------------------------
def i... |
9d65a586ce67c49cff3abe359768a85eedee9411 | Amran-Lab/python | /fizzbuss.py | 500 | 3.875 | 4 | #!/usr/bin/env python3.8
def fizzbuzz(b):
for i in range(1,b+1):
if i%5==0 and i%3==0:
print("FizzBuzz", i)
elif i%3==0:
print("Fizz", i)
elif i%5==0:
print('Buzz', i)
else:
pass
#fizzbuzz(30)
def fizz(b):
for i in range(1,b+1):
... |
808a4d09c57dc245b0fc32fa6a35d12719e15d45 | jiangyt2112/leetcode | /teewt.py | 3,671 | 3.859375 | 4 | class User(object):
def __init__(self,userid):
self.userid=userid
self.tweet=[]
self.follow=[]
def PostTweet(self,t):
self.tweet.append(t)
def Follow(self,userid):
self.follow.append(userid)
class Tweet(object):
def __init__(self,tweetid,seq):
sel... |
dc186ea5e84e78ab4721ec872da7c9f2b65696e2 | lchen8/cs342-lchen8-secret-sharing | /utils.py | 4,708 | 3.578125 | 4 | from operator import mul
from fractions import gcd
from random import randint
# Checks if n is pairwise relatively prime with every number in a list
def is_rel_prime(n, numlist):
for m in numlist:
if not n == m and not gcd(n, m) == 1:
return False
return True
# Helper funtions to return th... |
9abc4dd010f149887b27ba269b13e77b691c5eaa | htmlfinalproject/Hoja2 | /Hoja2.py | 521 | 3.984375 | 4 | #ejercicio 1
key = "contraseña"
password = input("Introduce la contraseña: ")
if key == password.lower():
print("La contaseña coincide")
else:
print("La contraseña no coincide")
#ejercicio 2
name = input("¿Cómo te llamas? ")
gender = input("¿Cuál es tu sexo (M o H)? ")
if gender == "M":
i... |
28d984906852d11a9afcbd0397aacb83cc248b82 | JacobBluhm/robotklubben | /make_dic.py | 1,451 | 3.625 | 4 | from stof_regi import *
def make_dic(gg):
def is_number(x):
try:
float(x)
return True
except ValueError:
return False
def upper(x):
return x == x.upper()
def last(x):
return is_number(x[-1])
def space(text):
if(last(text) == Fal... |
012530fe1e620760350113f8220b50795abfb2ae | sungkpark/derivativeSolver | /derivativesolver/terms.py | 4,843 | 3.671875 | 4 | import re
def solve_power(term):
if term[:1] == "x":
term = "1" + term
try:
coefficient,power = re.findall(r'(\-?\d+?)x\^?(\-?\d+)?', term)[0]
except IndexError:
coefficient, power = (1,1)
# print power
# parse
coefficient = int(coefficient)
if not power:
pow... |
62a09dba0d8fb5b6f08e7276ce80d6f8d91e1c79 | ri0452384/CMSC125 | /MP4-1.py | 4,727 | 4.09375 | 4 | """
This code will recognize the input string as either infix, prefix, or postfix, and generate its other counterparts from the given input
references:
http://interactivepython.org/lpomz/courselib/static/pythonds/BasicDS/InfixPrefixandPostfixExpressions.html
https://www.aoprogrammer.com/infix-prefix-and-postfix-n... |
c2fdf7eca2e571ab522f5c3d680d911aaed01c49 | Bradley-Agyei/Data-Structures-and-Algorithms | /Algorithms/recursive_binary.py | 579 | 4.09375 | 4 | def recursive_binary(list, target, start=0, end=None):
if end is None:
end = len(list) - 1
if start > end:
return -1
midpoint = (start + end) // 2
if target == list[midpoint]:
return midpoint
else:
if target < list[midpoint]:
return recursive_binary(list... |
f76d6958f8b08fcd00caab5a951d87d405400ef0 | dodoyeon/practice | /python_exer3.py | 4,675 | 3.8125 | 4 | # 집합 자료형 : set
# no = set(['Agent of sheild', 'Agent carter', 'Harry porter']) 이렇게는 안된다
n = set([1,2,3])
print(n)
m = set("Finn and Jake Adventure Time")
print(m) # {'t', 'a', 'J', ' ', 'd', 'e', 'v', 'n', 'r', 'm', 'A', 'u', 'T', 'F', 'i', 'k'}
# 비어있는 집합 자료형은 s = set()으로 만들수 있다
# 집합 자료형의 특징
# set("Finn and... |
d4d65989ddfd9498f735491d0d5922c6a9cb7213 | carlosbarcelos/TextAdventure | /src/Enemy.py | 1,371 | 3.703125 | 4 | '''
@title Text Adventure: Enemy Class
@author Carlos Barcelos
@date 06 January 2019
The enemy class with member veriables and functions.
'''
import src.stdlib as std # Import standard libraries
class Enemy():
def __init__(self, name, details, resources):
self.name = name
enemy = toEnemy(details,... |
341917fac086a506932a8f01dd6c54b8e6fb8ad0 | kredeal/dz1 | /6.py | 318 | 4 | 4 | # Пользователь вводит номер буквы в алфавите. Определить, какая это буква.
letter = int(input('Номер буквы английского алфавита (целое число от 1 до 26) : '))
print('Это буква {}'.format(chr(letter + 96)))
|
ef298deeb472b73eedd614165faeabba604ad3b7 | Sagar3195/Djanog-glassapp | /glass_class.py | 2,476 | 3.703125 | 4 | ##Identify type of glasses based on the chemical composition using classification algorithm
## Importing required libraries
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings('ignore')
##Loading dataset
data = pd.read_csv("gl... |
778b825dd6d9fc525030292508023898238c5fb1 | Ryan-Walsh-6/ICS3U-Unit5-05-Python | /mailing_address.py | 2,459 | 4.25 | 4 | #!/usr/bin/env python3
# created by: Ryan Walsh
# created on: January 2021
# this program formats a mailing address
def format_address(addressee_from_user, street_number_from_user,
street_name_from_user, city_from_user, province_from_user,
postal_code_from_user, apt_number_from_... |
a2849be4fbb03463967a314c266f831fc3e14e21 | Mengfan-Shi/Connected-Devices | /iot-device/apps/tests/labs/Module02Test.py | 1,302 | 3.65625 | 4 | import unittest
"""
Test class for all requisite Module02 functionality.
Instructions:
1) Rename 'testSomething()' function such that 'Something' is specific to your needs; add others as needed, beginning each function with 'test...()'.
2) Import the relevant modules and classes to support your tests.
3) Run this cl... |
4f83c39ddcbd72b500ab9769798a6f295ad250b4 | RalfiCode/Introduction | /Introduction/Lesson8/function8.py | 363 | 3.625 | 4 | def mail() -> str:
isim = input("Isim igiriniz: ")
soyad = input("Soyad giriniz: ")
domain = input("Domain giriniz: ")
if not domain:
return "{}.{}@bilgeadam.com".format(isim,soyad)
else:
return "{}.{}@{}".format(isim,soyad,domain)
a = mail()
print(a)
print(type(a))
print("Mail meto... |
f65dad211366104cee5282e2acba0f160ae980e5 | RalfiCode/Introduction | /Introduction/Lesson5/Loops.py | 96 | 3.546875 | 4 | #while True:
#print("Sonsuz Döngü")
index = 0
while index < 100:
print(index)
index += 2
|
bd5524a72a443d8094358d22b23d2cab09cb7ade | RalfiCode/Introduction | /Introduction/Lesson15/Ornek3.py | 484 | 3.796875 | 4 | from abc import ABCMeta, abstractmethod
class BaseClass(metaclass = ABCMeta):
__metaclass__ = ABCMeta
@abstractmethod
def printerMetot(self):
return("Base Dosya")
class Personel(BaseClass):
def printerMetot(self):
return "Personel Dosyası Yazdırlıdı"
class Ogrenci(BaseClass):
def... |
b5b6224e872726cc645b83192490111a535bcbd6 | RalfiCode/Introduction | /Introduction/Lesson8/function2.py | 188 | 3.765625 | 4 | def tekcift(a):
if a == 0:
return 0
elif a % 2 == 0:
return 1
else:
return -1
result = tekcift(int(input("Lütfen bir sayı giriniz: ")))
print(result)
|
5c19b422f869c602e53a395f0900810f55019a78 | dmthvlngm/caltech-learning-from-data | /hw2_linearregression.py | 2,106 | 3.734375 | 4 | import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from hw1_perceptron import PLA
d = 2
N = 100
N_PLA = 10
check = False
def add_bias(data):
return np.hstack([np.ones(data.shape[0]).reshape(-1,1),data])
#class LinearRegression:
# def __init__(self):
# s... |
de88e20f0317128a1582c7def0325c75c9bdc303 | elijah-micho/learning_projects_reddit | /venv/magic8ball.py | 407 | 3.90625 | 4 | import random
def askQuestion():
repeat = "Yes"
while repeat == "Yes":
question = str(input("Ask me a yes or no question!"))
answers = ['It is certain.', 'Definitely no.', 'Reply hazy, try again.']
ball_answer = random.randint(0,2)
print(answers[ball_answer])
repeat =... |
89f1eb948922b86394ffa645bb65e61fb0a42029 | salmanomar97/PythonWork | /Advanced Math Functions/SOtriFun.py | 6,011 | 4.21875 | 4 | #Salman Omar, section 03
#This program is the function program that will do all the math for the main program
import math
def duplicatePts(x1,y1,x2,y2,x3,y3):
# Find if there are duplicate points in the triangle
if (x1,y1)==(x2,y2):
print("true")
return True
elif (x2,y2) == (x3,y3):
print("Dup... |
b8c78eac2afac4b33eb7528f10e7fc3ad38e6d98 | grantcurell/learn_to_program | /challenge_1/challenge1.py | 148 | 4.03125 | 4 |
number = int(input('Dame un número:'))
if number < 100:
print("\nTu número es menos que 100")
else:
print("\nTu número es 100 o más")
|
2c2ac2229163eaa38413d719391ea7d12423a1e1 | rmrsint/TI2BioP | /pseknc_mod.py | 10,764 | 4 | 4 | #!/usr/bin/python
# -----------------------------------------
# PseKNC - 06/11/2014
# Jordan Brooker
# Jrdnbrkr@gmail.com
# -----------------------------------------
from __future__ import division
import Data
import math, string, re, sys, getopt
# _mean: Calculates mean value of a list of numbers
# ---------------... |
4a102f9030738ab1d644836bfc0c2cda4ddb1574 | Auggers/Python_Learning | /AdventureGame.py | 11,523 | 3.90625 | 4 | #Imports
import os
import sys
from random import randrange
#For clearing the console after entering each room
clear = lambda: os.system('clear')
#Directions
North = "1 leading North"
South = "1 leading South"
East = "1 leading East"
West = "1 leading West"
#Enemy Damage info here
goblinAlive = True
monsterAlive = Tr... |
34afa06f4b2c533fd093e2659605c17c5e5ff16c | KaraMaedje/My-Student-App | /mycalendarGUI.py | 1,014 | 3.59375 | 4 | from graphics import*
from button import*
import calendar
def mycalendar():
win = GraphWin("My Calendar", 360, 360)
win.setCoords(0, 0, 360, 360)
win.setBackground("MistyRose")
# Title and Border
school = Text(Point(176, 302), "My Calendar")
school.setFace("arial")
school.set... |
f34e8262aa8f8f473a242a108aec9db39764fb97 | a-tal/pyweet | /pyweet/colors.py | 2,316 | 3.515625 | 4 | """Adds some color to the tweets."""
import re
from blessings import Terminal
class Term(object):
"""Static class to store terminal color info."""
@staticmethod
def colors():
"""Returns the colors in use for this terminal."""
if not hasattr(Term, "_colors"):
Term._colors = ... |
ff49d71777a06c1ffe95decdb6e7bfe1266b15cc | angadaws/LeetCode | /mergeTwoLists.py | 1,581 | 3.9375 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
p1 = l1
p2 = l2
ret = None
pret = None
while... |
a9d75390be0db04ea854ce850503d66642815413 | angadaws/LeetCode | /LFUCache.py | 2,435 | 3.75 | 4 | from collections import OrderedDict
class LFUCache:
def __init__(self, capacity: int):
"""
LFUCache(int capacity) Initializes the object with the capacity of the data structure.
"""
self.capacity = capacity
self.useCounter = OrderedDict()
self.currentCapacity = 0
... |
0126f9b56b7e9cb34c7ecce4013571ff98ef3014 | abolisetti/Pizza-Paint | /Random tests/week2bronze.py | 276 | 3.578125 | 4 | #Week2Bronze
g=int(input())
for i in range(g):
print(("GGGGG")*g)
for i in range(g):
print("G"*g,"...."*g,sep="")
for i in range(g):
print("G"*g,".."*g,"GG"*g,sep="")
for i in range(g):
print("G"*g,"..."*g,"G"*g,sep="")
for i in range(g):
print("GGGGG"*g)
|
9c8cdf63a583237310367d32eb11067b06f7922a | jnuho/jnuho.github.io | /chap02/max.py | 816 | 3.65625 | 4 | from typing import Any, Sequence
# Any : 제약이 없는 임의의 자료형
# Sequence : 시퀀스형 (list, bytearry, str, tuple, bytes)
# function주석 a는 Sequence타입, 리턴 타입 Any
def max_of (a: Sequence) -> Any:
"""시퀀스형 a원소의 최대값을 반환"""
maximum = a[0]
for i in range(1, len(a)):
if a[i] > maximum:
maximum = a[i]
... |
07e0a2f9021628b5baeeb84cb5fce3482a11c0e6 | acpfog/python | /6.00.1x_scripts/Week 4/Queez/problem7.py | 773 | 3.921875 | 4 | #
# Write a function called dict_interdiff that takes in two dictionaries (d1 and d2).
# The function will return a tuple of two dictionaries: a dictionary of the intersect of d1 and d2 and a dictionary of the difference of d1 and d2
#
def dict_interdiff(d1, d2):
r1 = {}
r2 = {}
for key in d1.keys() + d2.ke... |
a8fa29813cb4291a39db8d93c46ff0c9c8d5bded | acpfog/python | /6.00.1x_scripts/Week 8/Final Exam/problem3.py | 966 | 4.46875 | 4 | #
# dict_invert takes in a dictionary with immutable values and returns the inverse of the dictionary.
# The inverse of a dictionary d is another dictionary whose keys are the unique dictionary values in d.
# The value for a key in the inverse dictionary is a sorted list of all keys in d that have the same value in d.
... |
ccb58e3365e0bbfc25781cee9c118715a0493513 | acpfog/python | /6.00.1x_scripts/Week 2/do_polysum.py | 979 | 4.3125 | 4 | # A regular polygon has 'n' number of sides. Each side has length 's'.
# * The area of regular polygon is: (0.25*n*s^2)/tan(pi/n)
# * The perimeter of a polygon is: length of the boundary of the polygon
# Write a function called 'polysum' that takes 2 arguments, 'n' and 's'.
# This function should sum the area and squa... |
00c649a39b368c13b356ea399d8fb60b66d76dec | TSamson-QA/Python_programs | /debugging/debugging.py | 589 | 3.828125 | 4 | import pdb
#Ex 1
'''
user_funds = 10.31
item_price = 5.30
if item_price < user_funds:
print("You have enough money!")
if item_price == user_funds:
print("You have the precise amount of money")
if item_price > user_funds:
print("Sorry you don't have enough money")
'''
#Ex 2
'''
def product(n):
total ... |
a7699c41987cbf101e478a6a1623e5bf83221997 | paw39/Python---coding-problems | /Problem13.py | 1,257 | 4.34375 | 4 | # This problem was asked by Amazon.
#
# Run-length encoding is a fast and simple method of encoding strings.
# The basic idea is to represent repeated successive characters as a single count and character.
# For example, the string "AAAABBBCCDAA" would be encoded as "4A3B2C1D2A".
#
# Implement run-length encoding and d... |
261e8bdcd26d998737654e21ddfbc3c5285743d7 | zzzzz1797/design_pattern_python | /structural/adapter.py | 1,752 | 4.46875 | 4 | """
适配器模式(Adapter pattern)是一种结构型设计模式,帮助我们实现两个不兼容接口之间 的兼容。
详细:
如果我们希望把一个老组件用于一个新系统中, 或者把一个新组件用于一个老系统中,不对代码进行任何修改两者就能够通信的情况很少见。
但又并非总是能修改代码,或因为我们无法访问这些代码(例如,组件以外部库的方式提供),或因为修改代码本身就不切实际。
在这些情况下,我们可以编写一个额外的代码层,该代码层包含 让两个接口之间能够通信需要进行的所有修改。这个代码层就叫适配器。
"""
from typing import Dict
class Comput... |
34670ddc3aea33f7976d4836733dd37ef0176977 | Mayni91/Pathfinding_Simulator | /Vector2D.py | 1,397 | 3.5 | 4 | import math as math
import random as random
class Vector2D:
dx = 0
dy = 0
def __init__(self, dx=0, dy=0):
self.dx = dx
self.dy = dy
def print(self):
print("Vector2D(x: " + self.dx + ", y: " + self.dy + ")")
def normalize(self):
self.dx /= self.mag()
self.... |
da304c9a786c2d7ec5583af23ba2fe96c4fff9e0 | fhumanity/proje27 | /proje27.py | 15,092 | 3.828125 | 4 | import time
import random
import datetime
import sqlite3
class user():
def __init__(self,name,point,last_date):
self.name = name
self.point = point
self.last_date = last_date
def __str__(self):
return "Kullanıcının Adı : {}\nKullanıcının Puanı : {}\nKullanıcının son girişi :{}\n... |
a7e7442e0a638f9d1fe5d43bf361ea8ab02fa746 | toohong5/algorithm | /191007/memoization.py | 712 | 3.578125 | 4 | def fibo(n):
global cnt
cnt += 1
if n >= 2 and memo[n] == -1: # 한 번도 호출 안된 경우만 if문 수행
memo[n] = fibo(n-1) + fibo(n-2)
return memo[n] # 리스트의 인덱스값 호출
N = int(input())
cnt = 0
memo = [-1] * (N + 1) # -1 이면 한번도 호출 안된 경우임..
memo[0] = 0
memo[1] = 1
print('피보나치 결과: ', fibo(N))
print(memo)
print('호출 횟... |
22f515ac9e1206ec963b941dd7222b9962bf8cde | balamurugan1999v/prolevel | /setpro53.py | 163 | 3.609375 | 4 | s1=[]
a=input().split()
for i in a:
for k in i:
if k not in s1:
s1.append(k.lower())
#print(s1)
p=len(s1)
if p==26:
print('yes')
else:
print('no')
|
bfa28a01e5a1a43604b4ecf982c59e77c6e641d8 | HS4MORVEL/Lintcode-solution-in-Python | /109_triangle.py | 1,879 | 4 | 4 | '''
Given a triangle, find the minimum path sum from top to bottom.
Each step you may move to adjacent numbers on the row below.
Notice
Bonus point if you are able to do this using only O(n) extra space,
where n is the total number of rows in the triangle.
Have you met this question in a real interview? Yes
Example... |
439a16760655b3bd6ec5a4d114ccb2a15e736306 | HS4MORVEL/Lintcode-solution-in-Python | /069_binary_tree_level_order_traversal.py | 1,557 | 4 | 4 | '''
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
Have you met this question in a real interview? Yes
Example
Given binary tree {3,9,20,#,#,15,7},
3
/ \
9 20
/ \
15 7
return its level order traversal as:
[
[3],
[9,20],
... |
884c4f2ea10f76baf17dfdf6e986a84b39bff060 | HS4MORVEL/Lintcode-solution-in-Python | /016_permutation_II.py | 1,343 | 3.90625 | 4 | '''
Given a list of numbers with duplicate number in it. Find all unique permutations.
Example
For numbers [1,2,2] the unique permutations are:
[
[1,2,2],
[2,1,2],
[2,2,1]
]
'''
class Solution:
"""
@param: : A list of integers
@return: A list of unique permutations
"""
def permuteUnique(se... |
f40e03b6e5812149476681db8ddc24fd22e2063b | HS4MORVEL/Lintcode-solution-in-Python | /004_ugly_number_II.py | 1,009 | 4.25 | 4 | '''
Ugly number is a number that only have factors 2, 3 and 5.
Design an algorithm to find the nth ugly number.
The first 10 ugly numbers are 1, 2, 3, 4, 5, 6, 8, 9, 10, 12...
Notice
Note that 1 is typically treated as an ugly number.
Example
If n=9, return 10.
Challenge
O(n log n) or O(n) time.
'''
from heapq imp... |
3864e9b9cd6c545cf46c48794d65295e2f51514e | fe-sts/curso_em_video | /Python 3 - Mundo 1/1. Tratando dados e fazendo contas/Exercicio 008.py | 301 | 4 | 4 | #Escreva um programa que leia um valor em metros eo exiba convertido em centímetros e em milimetros
n1 = float(input('Entre com o valor em metros (use .(ponto) para valores quebrados):'))
print('Para o valor {} m \n Equivale a: \n {} centímetros \n {} milímetros'.format(n1, n1*(100), n1*(1000))) |
9c5a6ef9326bc0c77a197ba0ffd327d436d12253 | fe-sts/curso_em_video | /Python 3 - Mundo 1/3. Condições em Python (if..else)/Exercicio 031.py | 453 | 3.953125 | 4 | #Desenvolva um programa que pergunta a distância de uma viagem em km.
#Calcule o preço da passagem, cobrando R$0,50 por km para viagens de até 200km e R$0,45 para viagens mais longas
dist_viagem = float(input('Digite a distância de sua viagem em km: ').strip())
if dist_viagem <= 200:
print('O preço da passagem é R... |
4cf2e4c7ad4bdd2a9f80a0aa3de54c4c4f0e4270 | fe-sts/curso_em_video | /Python 3 - Mundo 2/4. Repetições em Python (while)/Exercicio 71.py | 1,030 | 4.15625 | 4 | '''
Crie um programa que simule o funcionamento de um caixa eletrônico.
No inicio, pergunte ao usuario qual será o Valor a ser sacado (numero inteiro) eo programa vai informar quantas
cédulas de cada valor serão entregues.
Considere que o caixa possui cédulas de 50, 20, 10 e 1 real.
'''
print("=======Sistemas Caixa ... |
b22de71fd132ee26d8c1a06d4c5812044a0be38d | fe-sts/curso_em_video | /Python 3 - Mundo 2/4. Repetições em Python (while)/Exercicio 066.py | 492 | 4.09375 | 4 | #Crie um programa que leia varios numeros inteiros pelo teclado.
#O programa só vai parar quando o usuário digitar 999, que é a condição de parada.
#No final mostre quantos numeros foram digitados e qual a soma entre eles (desconsiderando o flag "999")
#Utilizar break
num = cont = 0
while True:
num = int(input('Di... |
a2e8f9543125bc00e9f3239e12fac04fa3c7af3b | fe-sts/curso_em_video | /Python 3 - Mundo 2/4. Repetições em Python (while)/Exercicio 068.py | 922 | 3.921875 | 4 | '''
Faça um programa que jogue Par ou Impar com o computador.
O jogo só será interrompido quando o jogador Perder, mostrando o total de vitórias consecutivas que ele conquistou no final do jogo.
'''
from random import randrange
num = 0
tipo = ''
num_comp = 0
resultado = ''
vitorias = 0
print('='*60)
print('JOGO IMPAR... |
161200af3074fd3ca367af21f7099b73cef4ebbd | fe-sts/curso_em_video | /Python 3 - Mundo 3/2. Listas/Exercicio 079.py | 662 | 4.15625 | 4 | '''
Exercício Python 079: Crie um programa onde o usuário possa digitar vários valores numéricos e cadastre-os em uma lista.
Caso o número já exista lá dentro, ele não será adicionado.
No final, serão exibidos todos os valores únicos digitados, em ordem crescente.
'''
lista = []
num = 0
continua = ''
while True:
... |
58d3ee15b5fd9b10272478788fd0d7685500f6e5 | fe-sts/curso_em_video | /Python 3 - Mundo 3/2. Listas/Exercicio 082.py | 848 | 4.0625 | 4 | '''
Exercício Python 082: Crie um programa que vai ler vários números e colocar em uma lista.
Depois disso, crie duas listas extras que vão conter apenas os valores pares e os valores
ímpares digitados, respectivamente. Ao final, mostre o conteúdo das três listas geradas.
'''
lista_pares = []
lista_impares = []
list... |
d5af722c323a4b788028ca18fc68d20d56ea6bf6 | fe-sts/curso_em_video | /Python 3 - Mundo 1/3. Condições em Python (if..else)/Exercicio 032.py | 441 | 3.96875 | 4 | #Faça um programa que leia um ano qualquer e mostre se ele é bissexto
from datetime import date
ano = int(input('Digite o ano para saber se é Bissexto: '))
if ano == 0:
ano = date.today().year
if (ano % 4) == 0:
if ((ano % 100) != 0) or (ano % 400) == 0:
print('O ano {} é bissexto!'.format(ano))
el... |
6bc2f8c3d6259e959139b4fc98d9ab5621c89704 | fe-sts/curso_em_video | /Python 3 - Mundo 1/1. Tratando dados e fazendo contas/Exercicio 004.py | 431 | 3.796875 | 4 | algo1 = input('Digite algo: ')
print('O tipo primitivo desse valor é: ', type(algo1))
print('Só tem espaços? ', algo1.isspace())
print('É um número? ', algo1.isnumeric())
print('É alfabético? ', algo1.isalpha())
print('É alfanumperico? ', algo1.isalnum())
print('Está em maiúsculas? ', algo1.isupper())
print('Está em m... |
9bc6e1883219e65b6d956f3b624a2d818679d502 | fe-sts/curso_em_video | /Python 3 - Mundo 1/1. Tratando dados e fazendo contas/Exercicio 014.py | 347 | 4.15625 | 4 | #Converter graus celsius em farenheit e kelvin
celsius = float(input('Entre com a temperatura em graus Celsius (ºC): '))
farenheit = (((9 * celsius) / 5) + 32)
print('A temperatura de {0}ºC corresponde a {1} ºF'.format(celsius, farenheit))
kelvin = celsius + 273
print('A temperatura de {0}ºC corresponde a {1} ºK'.for... |
c93218bd652f5da26c651247cc37913a371f5236 | fe-sts/curso_em_video | /Python 3 - Mundo 1/2. Usando módulos do Python/Aula 008.py | 313 | 3.859375 | 4 | #from math import sqrt
#num = int(input('Digite um numero: '))
#raiz = sqrt(num)
#print('A raiz quadrada de {} é: {:.2f}'.format(num, raiz))
#import random
#num = random.randint(1, 10) #Randomizar um numero de 1 a 10
#print(num)
#import emoji
#print(emoji.emojize('Olá, mundo :sunglasses:', use_alises=True)) |
33fab8dd21256c3f107d68652af5e6cc9216809a | athina-rm/extra_labs | /extralabs_basic/extralabs_basic.py | 343 | 4.15625 | 4 | #Write a Python program display a list of the dates for the 2nd Saturday of every month for a
#given year.
from datetime import datetime
year=int(input("enter the year:"))
for j in range(1,13):
for i in range (8,15):
dates =datetime(year,j,i)
if dates.strftime("%w")=="6":
print(dates.s... |
a6737f8bc4d71bb4d48b3b62c8145626a578007e | athina-rm/extra_labs | /extralabs_basic/module5.py | 273 | 4.375 | 4 | # Find
#Find all occurrences of “USA” in given string ignoring the case
string=input("Enter the string : ")
count=0
count=string.lower().count('usa')
if count==0:
print('"USA" is not found in the entered string')
else:
print(f'"USA" is found {count} times')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.