blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
d7790563e96a4b55eb234feaed0095e90c82f159 | codinglzc/liaoxuefengLearnPython | /functionalProgramming.py | 7,772 | 3.96875 | 4 | # coding=utf-8
import functools
# 函数式编程,允许把函数本身作为参数传入另一个函数,还允许返回一个函数!
# 高阶函数
# 变量可以指向函数
print abs
f = abs
print f
print f(-10)
# 函数名也是变量
# 传入函数
def add(x, y, f):
return f(x) + f(y)
print add(-5, 6, abs)
##############################################
# map/reduce
# python内建了map()和reduce()函数
# map:map()函数接收两个参数... |
0e9293005042e6630ddfee5ec8500859c5317fb5 | juanmed/riseq_uav | /riseq_tests/src/riseq_tests/utils.py | 901 | 3.5625 | 4 | import numpy as np
def saturate_scalar_minmax(value, max_value, min_value):
"""
@ description saturation function for a scalar with definded maximum and minimum value
See Q. Quan. Introduction to Multicopter Design (2017), Ch11.3, page 265 for reference
"""
mean = (max_value + min_value)/2.0
ha... |
bff4881dfe23a7c5b7a1cea4511551910d1f4b80 | alexasih/program-like-a-boss | /fall19-python/move-zeroes.py | 896 | 3.734375 | 4 | # ORIGINAL SOLUTION - REMOVES ZEROS EVEN IF ALREADY AT THE END
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
# if the zeros are before the next available integer, then swap
count = 0
... |
020d833a86a56d036550327ef3e39260337f9173 | alexasih/program-like-a-boss | /fall19-python/binary-tree-level-order-traversal.py | 2,396 | 4.09375 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def levelOrder(self, root: TreeNode) -> List[List[int]]:
# adding root node to queue
queue = [root]
... |
b1242aa733dfd35d4578da2963e2373c100bf139 | alexasih/program-like-a-boss | /fall19-python/add-two-numbers.py | 2,859 | 3.859375 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
# SOLUTION USING STACKS
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
stack1 = []
stack2 = []
ret_stack = []
... |
f3316300b43bef7eadc11dfdc9e1efa841f5009c | alexasih/program-like-a-boss | /fall19-python/find-duplicate.py | 1,502 | 3.75 | 4 | # First solution with O(n) for space
def find_repeat(numbers):
number_dict = {}
for n in numbers:
if n not in number_dict:
number_dict[n] = 1
else:
number_dict[n] += 1
for n in number_dict:
if number_dict[n] > 1:
return n
return "None"
#... |
91f400fcfce6734c1ea6cd209b70c3675cf0318f | kbfreder/coding-challenges | /Leetcode/palindrome_int | 1,261 | 3.890625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 13 18:58:23 2019
@author: kendra
"""
def palindrome_int_01(x):
s = str(x)
rev_s = ''
for x in range(1,len(s)+1):
rev_s += s[-x]
if rev_s == s:
return True
else:
return False
def palindrome_int_03(x):
... |
1a5065d28cafac985103dc371c67ab6ce94b2b63 | liu-justin/v1_two_axis_ros | /scripts/pointFinder.py | 7,736 | 3.703125 | 4 | import math
import numpy as np
import stepMath as smath
class Point:
def __init__(self, x, y, z=0):
self.x = x
self.y = y
self.z = z
def __str__(self):
returnString = "(" + str(self.x) + ", " + str(self.y) + ", " + str(self.z) + ")"
return returnString
# r... |
6facc80d44c0c8eef62240b79214bf5180ac1d40 | Happy-hacker0/PythonDailyTest | /day0914/test01.py | 1,111 | 4.125 | 4 | # int主要是用来计算的
"""
二进制和十进制互相转换
"""
# int
# bit_length: 有效的二进制长度
i = 4
print(i.bit_length()) # 3
i = 5
print(i.bit_length()) # 3
i = 10
print(i.bit_length()) # 4
# bool int str
# bool <---> int ***
"""
True 1 False 0
非零即True 0是False
"""
# str <---> int ***
"""
s1 = 10 int(s1):必须是数字组成
i = 100 str(i)
"""
# str <-... |
9a636d4e2a9919f11233c308eccabb3963b39256 | yusean/Program | /Python/PythonTest/src/OperatorsTest.py | 754 | 4.125 | 4 | #Python算术运算符
a = 10;
b = 20;
print(a + b);
print(a - b);
print(a * b);
print(a / b); #取模 - 返回除法的餘數
print(b % a); #幂 - 返回x的y次幂
print(a ** b);
print(9 // 2);#取整除 - 返回商的整数部分
a = 21
b = 10
c = 0
c = a + b
print("Line 1 - Value of c is ", c)
c = a - b
print("Line 2 - Value of c is ", c)
c = a * b
print("Line 3 - Value ... |
139b083b3e3ead1dba9d23a6e3f2a41755fb46c3 | Romainpkq/LAT_prediction | /Use_randomforest_reduce_dimension.py | 2,376 | 3.65625 | 4 | # This file is try to use random Forest to reduce the dimensions of features
from random import shuffle
import pandas as pd
import numpy as np
from skmultilearn.problem_transform import LabelPowerset
from sklearn.ensemble import RandomForestClassifier
import matplotlib.pyplot as plt
from scipy import sparse
from sci... |
ae80001fa90b0fb24e0c29c93f840156381c59d7 | yasser-khelalef/Python-test | /tests 2 & 3 & 4/functional.py | 4,176 | 4.15625 | 4 | def sum_of_int_str_items(list_of_strings):
# Assuring that the input is a none empty list containing only string elements
if type(list_of_strings)==list and len(list_of_strings)>=1 and all([isinstance(x,str) for x in list_of_strings]):
# Initializing the sum of the items to 0
sum_of_items = ... |
90d3a7df3a23daf2a1be421fbe24dafa8d0b4b94 | thejomas/projects | /dailyProgrammer/fac.py | 138 | 3.578125 | 4 | import sys
def fac(n):
fac = 1
for i in range(n):
fac *= (i+1)
return fac
n = int(sys.argv[1])
print('n!:', fac(n))
|
54115be3e304bf0ba86a72aa7c6d6f48ebc7cc32 | osori/cracking-the-coding-interview | /chapter1_arrays_and_strings/06_string_compression.py | 492 | 3.546875 | 4 | testcases = """aabcccccaaa
hongsoook
baaaabbboooo
abcd"""
def string_compression(string):
output = []
counter = 0
for i in range(len(string)):
if string[i] != string[i-1] and i != 0:
output.append(string[i-1]+str(counter))
counter = 0
counter += 1
concat = ''.jo... |
67763a892c86faca5c8a3b4eef21c1579658302f | nitinreddy3/interview_prep_python | /merge_intervals.py | 1,027 | 3.859375 | 4 | '''
Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).
Given intervals [1,3],[6,9], insert and merge [2,5] in as [1,5],[6,9].
[3,8]
[1,5] [5,10]
start_time = 1
end_time = 8
'''
def merge_intervals(intervals, new_interval):
end_time = None
start_time = None
r... |
91556d16bec72592699225da60ff28ac01bb7009 | jszendre/portfolio | /ComputationalScienceCoursework/Tree Data Structures and Algorithms/avl_and_bst_trees.py | 21,229 | 3.78125 | 4 | # trees.py
"""Volume 2A: Data Structures II (Trees).
<Name>
<Class>
<Date>
"""
from matplotlib import pyplot as plt
import random
import numpy as np
import pdb
import time
class SinglyLinkedListNode(object):
"""Simple singly linked list node."""
def __init__(self, data):
self.value, self.next = data, N... |
65a38a7d95e335e19c37381d3c9ab2e3a1f70d05 | ahmedkhaed/MultiLinear-Regression-with-taxi | /multilinear_regression_taxi 1py.py | 2,903 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Mar 14 02:17:42 2019
@author: Ahmed Khaled
"""
#Step 1 - Import the necessary libraries and the dataset
#Step 2 - Plot the Seaborn Pairplot
#Step 3 - Plot the Seaborn Heatmap
#Step 4 - Extract the Features and Labels
#Step 5 - Cross Validation (train_test_split)
... |
f3d81ffa371aeb976cb5752907ddd4d39fb83146 | kevapostol/holberton-system_engineering-devops | /0x16-api_advanced/0-subs.py | 573 | 3.546875 | 4 | #!/usr/bin/python3
"""
This module GETS data from an API
"""
import requests
def number_of_subscribers(subreddit):
"""
Returns the number of subscribers
Endpoint: /r/{}/about.json
"""
uri = "https://www.reddit.com"
headers = {'User-Agent': 'Chrome/81.0.4044.138'}
response = requests.get(u... |
571e10353a2e7dc25d3b18a478243d0205d91664 | va1ha11a/rjk_tools | /decorators.py | 1,562 | 3.703125 | 4 | from functools import wraps
def __string_args_key_gen(*args, **kwargs):
"""
Key gen function for dynamic programming.
Will create a string from args. Some issues might be seen with
deep data types if order is not consistant.
"""
key = (str(args), str(sorted(kwargs)),
str([kwargs[k] ... |
4ae44003338d2c4c7bb6f06c0cce00bea4a1b75b | shabbirkhan0015/python_programs | /time3.py | 340 | 3.953125 | 4 | import datetime
def next_weekday(d, weekday):
days_ahead = weekday - d.weekday()
if days_ahead <= 0: # Target day already happened this week
days_ahead += 7
return d + datetime.timedelta(days_ahead)
d = datetime.date(2011, 7, 2)
next_monday = next_weekday(d, 0) # 0 = Monday, 1=Tuesday, 2=Wednesday..... |
7fc9e560c28de7b2db6766a97f9b176c8da7cb9c | shabbirkhan0015/python_programs | /inheritance3.py | 354 | 3.984375 | 4 | class Address:
street_name="Massachusetts Ave"
number=77
def __init__(self,street,num):
self.street_name=street
self.number=num
class campusaddress(Address):
def __init__(self,officeaddress):
self.officeaddress=officeaddress
s1=campusaddress("b8-401")
print(s1.officeaddress)
prin... |
808d811887bf81801245cf9b8a48926ac8db16f4 | shabbirkhan0015/python_programs | /string1.py | 138 | 3.828125 | 4 | message =input("Enter message to encode: ")
print ("Decoded string (in ASCII):")
for ch in message:
print (ord(ch))
print ("\n")
|
9821e8bdb02ba4cc0022faccc63978459be69d11 | fleamon/self_study_python | /jumpToPython/ch5/ch5_python_1_class.py | 4,681 | 3.984375 | 4 | #-*- encoding: utf-8
res1 = 0
def add(num):
global res1
res1 = res1 + num
return res1
print add(3)
print add(4)
res2 = 0
def add2(num):
global res2
res2 = res2 + num
return res2
print add2(2)
print add2(3)
print """
If you need some calculator in one block?
If you can make it once and reuse i... |
e86ea4332069f973f01eeb81481238ac1938f0ae | jaroszew/Python_Zadania | /Zadania zajecia 3/funkcja3.py | 501 | 4.125 | 4 | #funkcja 3 nieskonczenie wiele stringów i lacznik
def Combine_String(*args, glue = ":"):
Combined_String =""
list_string = []
for string in args:
if len(string) > 3 :
list_string.append(str(string))
print(list_string)
Combined_String = glue.join(list_string)
return Combined_String
elements = i... |
096958fc4f4b811e17f0824ad2ff7d154f33a1a6 | gvermillion/research | /dft/potential_map/kpts/water_shifter_rotator.py | 2,044 | 3.578125 | 4 | #!/usr/bin/python
import sys
from math import *
def rotateAxisX(alpha):
'''
Rotation about x axis
:param alpha: plane altitude angle in rad
:return: x-axis rotation matrix
'''
rotX = [[1, 0, 0],
[0, cos(alpha), sin(alpha)],
[0, -sin(alpha), cos(alpha)]]
return rotX
def rotateAx... |
e93a504de0043422bb779e545432e434ca2c802d | twardoch/robofab | /Scripts/RoboFabIntro/demo_RoundKerning.py | 378 | 3.546875 | 4 | """round all kerning values to increments of a specified value"""
value = 100
from robofab.world import CurrentFont
font = CurrentFont()
kerning = font.kerning
startCount = len(kerning)
kerning.round(value)
font.update()
print 'finished rounding kerning by %s.'%value
print 'you started with %s kerning pairs.'%start... |
431d8c2887e0489c8ec4941e32f8063b2fc15d8f | UAL-AED/lab3 | /aed_ds/lists/adt_list.py | 2,613 | 4.03125 | 4 | from abc import ABC, abstractmethod
from aed_ds.adt_iterator import Iterator
class List(ABC):
@abstractmethod
def is_empty(self) -> bool:
"""Returns true iff the list contains no elements."""
@abstractmethod
def size(self) -> int:
"""Returns the number of elements in the list."""
... |
20d93ce79d7ad37c49c914289cfc04973ed73399 | abhishekshinde2104/Deep_Learning_A-Z | /CNN/CNN.py | 7,656 | 4.15625 | 4 | #Part 1:
#we wont use data preprocessing
#we just use feature scaling and image augmentation
#Part 2: Building the CNN
from keras.models import Sequential#initialise NN
from keras.layers import Convolution2D#1st step of CNN 2D for images CNN layer
from keras.layers import MaxPooling2D#2nd step pooling layers... |
b43c9bc6779aa48916116242d9b0bfb71c060537 | Wizard-Fingers/dic_val_and_while_loops | /main.py | 396 | 4.0625 | 4 | stu_gra = {"Harry": 66, "Joe": 77, "Tim": 88}
for grades in stu_gra.items():
print(grades)
for grades in stu_gra.keys():
print(grades)
for grades in stu_gra.values():
print(grades)
user_name = " "
while user_name != "Art":
user_name = input("Enter your name:")
username = " "
while True:
username = inpu... |
4b778a93deec9f82ad7d87bfbbeab63d85c17880 | TheOceanPony/Pattern_Recognition | /Bayesian/First/FirstModule.py | 1,643 | 3.671875 | 4 | import math
# TODO write a description for each function
def parse_even(arr, index=0):
result = []
for i in range(index, len(arr)):
if i % 2 == 0:
result.append(arr[i])
return result
def parse_odd(arr, index=0):
"""
>>> parse_odd([1,0,1,0,1,0,1,0,1,0])
[0, 0, 0, 0, 0]
... |
36b2b772a6f545c013ddb38338a4553ae6a1c36f | LeiaPark/SoftDev_WorkRepo | /fall/18_db-nmcrnch/stu_mean.py | 1,771 | 4.0625 | 4 | # Team Bunnytruffles: Jeff Lin, Leia Park
# SoftDev1 PD9
# K18 -- Average
# 2019-10-14
import sqlite3 #enable control of an sqlite database
import csv #facilitate CSV I/O
DB_FILE="school.db"
db = sqlite3.connect(DB_FILE) #open if file exists, otherwise create
c = db.cursor() #facilitate db ops
... |
0688b651fc308797056f62504c090777728af133 | jwebster7/sorting-algorithms | /bubble_sort.py | 1,135 | 4.34375 | 4 |
def bubbleSort(lst):
'''
1. On the first iteration, compare all the elements (n). For the subsequent runs, compare (n-1) (n-2) and so on.
2. Compare each element (lst[i]) with its right side (lst[i + 1]) neighbour.
3. Swap the smallest element to the left.
4. Repeat steps 1-3 until the whole list i... |
a79b117671393cecb85f6b55631accb186f0e298 | taism-ap/hw-3-3-python-list-problems-kalindik | /find_number.py | 395 | 3.796875 | 4 | from random import randint
def random_list(largest,size):
l = []
for i in range(size):
n = randint(0,largest -1)
l.append(n)
return(l)
def find_number(l):
count = 0
for i in l:
if (i == num):
count +=1
return (count)
l = random_list(10,10)
print (l)
num = int(input("Type a number fr... |
24a5eab65d3ec60a7db1b741bc1f0ce2516a4f81 | kunalgaurav4/100-PythonProgrammingQuestion | /1.divisible.py | 398 | 3.78125 | 4 | '''
Write a program which will find all such numbers which are divisible by 7 but are not a multiple of 5,
between 2000 and 3200 (both included).
The numbers obtained should be printed in a comma-separated sequence on a single line.
'''
first = int(input())
last = int(input())
l = []
for i in range(first, last+1):
... |
1c71b7c839495648d6f7591e255f7b3c67b41e75 | sahiljain443/Learn_python | /Employee.py | 1,591 | 3.84375 | 4 | #Python Object-Oriented Programming
class Employee:
raise_amt = 1.04
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + '.' + last + '@company.com'
def fullname (self):
return '{} {}'.... |
a384f5015d194dc9e04ce94f301be27194cad72e | joebattles/puzzles | /leap/leap.py | 238 | 3.84375 | 4 | def leap_year(year):
print(year)
temp1 = (year % 4)
temp2 = temp1 + (year % 100)
temp3 = temp2 + (year % 400)
if (temp1 == 0) and (temp2 >= 1 or temp3 == 0):
x = True
else:
x = False
return x
|
6aa887a9369c306f12b48f4e8b9725b9299dc3bb | vishakraj25/Fraper | /newyorktimes.py | 1,857 | 3.53125 | 4 | """
Author : Vishak Raj
E-mail ID : vishak.shanmu@gmail.com
Gives and save the news from the nytimes news paper
And nytimes have limitaiton, to get full access contact the nytimes
"""
import json
import requests
# Refer the doc - https://developer.nytimes.com/docs/articlesearch-product/1/routes/articlesearch.json/g... |
d493f997a0c6ae388b832a3ed192d78c70655729 | mverzett/katas | /differentiation-kata/differentiation.py | 683 | 4.03125 | 4 |
# https://www.codewars.com/kata/symbolic-differentiation-of-prefix-expressions/train/python
import unittest
### differentation rules, assume to differentiate for x
###
### f(x) == (f x) => f'(x)
### (cos x) => (- (sin x))
### (sin x) => (cos x)
### (* n x) => n
### (* n (^ x m) => (* n (* m (^ x (- m 1))))
### (* (... |
09f523acbcac8c28ff8b7d3576dc10beb3111958 | RajShekhorRoy/Learning_Machine_Learning | /neural_network_simple.py | 1,169 | 3.859375 | 4 | ## Acknowledment code taken from https://stackabuse.com/creating-a-neural-network-from-scratch-in-python/
import numpy as np
def sigmoid(x):
return 1 / (1 + np.exp(-x))
def sigmoid_der(x):
return sigmoid(x) * (1 - sigmoid(x))
feature_set = np.array([[0, 1, 0], [0, 0, 1], [1, 0, 0], [1, 1, 0], [1, 1, 1]]... |
8b091f2c9d75eaa193857c95b38423be9112b7bd | TengPan2011/testwebapp | /hello.py | 318 | 3.65625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Apr 23 16:57:06 2019
@author: Teng Pan
"""
from flask import Flask
#Flask objects are initialized with name of this file
app = Flask(__name__)
#Call the route function here, passing in hello world as the function
@app.route('/')
def hello_world():
return 'Hello, World!' |
1bf15c68715c50742dc69a64da8c1a14df49e9c2 | arihantbansal/cybersec-python | /Cryptography/fixed_xor.py | 153 | 3.796875 | 4 | def xor(a, b):
return hex(int(a, 16) ^ int(b, 16))
a = input("Enter first string to XOR: ")
b = input("Enter second string: ")
print(xor(a, b)[2:])
|
4608d637a698526e4f4983c6be31a3adaa2c1609 | idristuna/python_exercises | /basic_exercise/excerise1.py | 173 | 3.78125 | 4 | #! /usr/bin/python3
name = input("Please enter your name: ")
age = int(input("Please enter you age: "))
print(name + " you will be " + str(age+100) + " in hundered years")
|
34c9b9b695afc0636244ee59e764737a4720e9e7 | idristuna/python_exercises | /basic_exercise/q8.py | 76 | 3.65625 | 4 | #! /usr/bin/python3
for i in range (1,6):
print(str(i)*i)
i = i +1
|
9a90c40ba3ffd774df3fec0b8abb2e7f80373dbe | idristuna/python_exercises | /basic_exercise/q2v2.py | 399 | 3.9375 | 4 | #! /usr/bin/python3
def sumNum(num):
previousNum = 0
for i in range(num):
sum = previousNum + i
print("Current number ", i, " Previous number ", previousNum, " sum ", sum )
previousNum = i
print("Printing current and previosu number and sum give range(10)")
sumNum(10)
print("\n")
pr... |
3975238562c10b682c6fab3ab5331ed61a8f1717 | wangke-tech/DataStructure | /ds/BTree.py | 1,883 | 3.71875 | 4 | #!/usr/bin/env python
# encoding: utf-8
from collections import namedtuple
from io import StringIO
# define the node structure
Node = namedtuple('Node', ['data','left','right'])
# initialize the tree
tree = Node(1,
Node(2,
Node(4,
Node(7, None, None),
... |
a25d6afe0d7c0f651255d605084df52bfe922b0e | shiverenje/fredrick-kiverenge-bootcamp-17 | /Day 2/object_oriented_test.py | 1,400 | 3.921875 | 4 | import datetime
class Vehicle(object):
num_of_wheels = 4
milage = 0
manufacturer = 'Toyota'
def __init__(self):
self.manufacturer = Vehicle.manufacturer
self.milage = Vehicle.milage
self.num_of_wheels = Vehicle.num_of_wheels
def get_year(self):
t =dateti... |
cd8237358967f0890d6c3808219761cd644ec409 | shiverenje/fredrick-kiverenge-bootcamp-17 | /Day4/find_missing.py | 237 | 3.828125 | 4 | def find_missing(n, m):
if n == [] and m == []:
return 0
elif n == m:
return 0
else:
return set(n) ^ set(m)
a = [5, 4, 7, 6, 11, 66]
b = [5, 4, 1, 7, 6, 11, 66]
print(find_missing(a, b))
|
0b9f0181cb2313b39fe4b85d2f24ee9337aebde2 | PopaGabriel/Pandas-sketchbook | /pythonProject2/Numpy_Notebook.py | 2,128 | 4.4375 | 4 | import math
import numpy as np
print('why not?')
# to create a vector of zeros we use the np.zeros command
# we send the size in a list the column in the right and the
v = np.zeros([2, 4])
v = v + 2
# v[10][3] = 1001
# print(v)
# Multiplication should be done using np.dot(vector, vector) because it is incredibly ... |
6d95c5167c09342d84830bc700a146394f4344a5 | StuckBoy/CS495 | /Loops/Recursion.py | 1,586 | 4.21875 | 4 | def count(num):
"Takes the given number and counts up to it while printing."
if(num >= 1):
count(num-1)
print(num)
def fac(n):
"Takes in a given number and calculates the factorial of it"
if(n == 1):
return 1
else:
return n * fac(n-1)
def spacer(count, character):
... |
3f7e39b0950d79dd412781cd60dc2841d715019d | pratyushagnihotri03/Python_Programming | /Python Files/8_ReturnValue/main.py | 304 | 3.71875 | 4 | def allowed_dating_age(my_age):
girls_age = my_age/2 + 7
return girls_age
my_dating_limit = allowed_dating_age(27)
print("Pratyush can date girls", my_dating_limit, "or older")
my_brother_dating_limit = allowed_dating_age(25)
print("Brother can date girls", my_brother_dating_limit, "or older") |
75edbee386f7fd1468b9b9446b2b4f90e635a5ba | MaximSungmo/practice01 | /prob10.py | 602 | 3.671875 | 4 | # 숫자를 입력 받아서 아래와 같은 실행결과가 나타나도록 코드를 완성하세요.
flag=True
while(flag):
number = input('숫자를 입력하세요 :')
result = 0
if number.isdigit() :
number = int(number)
if number % 2 == 0:
for i in range(0, number+1, 2):
result = result + i
else :
for i in range(... |
12f1c1256d723c67877a447c79bbbd2558564078 | deltonmyalil/PythonInit | /oddList.py | 134 | 3.8125 | 4 | oddlist1 = [2*x+1 for x in range(50)]
print(oddlist1)
oddlist2 = [x for x in range(100)]
oddlist3 = oddlist2[1:100:2]
print(oddlist3) |
2a1a1ae89bbf5b1555516e708945115d12662bc6 | deltonmyalil/PythonInit | /regExpFindAndReplace.py | 271 | 3.96875 | 4 | import re
string = "My name is delton and Hi Im delton"
pattern = r"delton"
newstring = re.sub(pattern,"Antony",string)#sub function takes the input pattern, string to replace and sourcec string variable to operate on. It will return the repllaced string
print(newstring) |
16f9e2ec6d983c38ecbbfbc00b9b676624c6a3db | deltonmyalil/PythonInit | /stack2.py | 433 | 3.890625 | 4 | stack = []
while(True):
response = int(input("Enter Op: 1-Push; 2-Pop; 3-Disp; 4-Exit>>>"))
if response == 1:
stack.insert(0,input("Enter item to push>>>"))
elif response == 2:
if stack == []:
print("Underflow")
else:
print("Dequeued item ", stack[0])
... |
38af8a4d6a45c2966bc26580ba6cdcf94935c260 | deltonmyalil/PythonInit | /dictionaryPrices.py | 704 | 4.03125 | 4 | products = {
"book":30,
"pen":20,
"eraser":5,
"calculator":800,
"glasses":1500,
"wallet":1750
}
flag = True
while(flag):
thing = input("Enter the item to check price>>>")
if thing in products:
print("price of the {0} is {1}".format(thing,products.get(thing)))
else:
pr... |
18ca5f068c0b7ae18fc1c8da9fb7b5e6f33e2718 | muzafferjoya/Python-Code | /Two and Square.py | 124 | 3.671875 | 4 | def two_and_square(count,num=-1):
if count<1: return
num=(num+2)**2
print(num); count-=1
two_and_square(count,num)
|
4fa8d95fd4f34a88baea6047c96a8de5400534df | tli4/csce-482-ml | /clusterer.py | 1,738 | 3.796875 | 4 | from sklearn.cluster import SpectralClustering
import numpy as np
class Clusterer:
"""This class encapsulates functionality of clustering
organizations. The clustering algorithm this class uses
is Spectral Clustering.
Attributes:
cluster_count (int): The number of clusters generated.
... |
c899134f353db6c652757d30ad11c24c61e12e73 | khushic/spg_codingcomp2020 | /Shells/Intermediate/Python/B.py | 164 | 3.96875 | 4 | def average(n):
#TYPE CODE HERE
return -1
n = input()
n_list = n.split(", ")
n_ints = []
for i in n_list:
n_ints.append(int(i))
print(average(n_ints)) |
d8a9d5dd628d48ad329cf04dbb69126806c2330c | khushic/spg_codingcomp2020 | /Beginner Solutions/A Georges Word Scrambler/GeorgesWordScrambler.py | 66 | 3.65625 | 4 | def reverse(str):
return str[0:0:-1]
print(reverse(input()))
|
a9c6de81393b6a399c2fb4abf581f5c672a291d7 | khushic/spg_codingcomp2020 | /Beginner Solutions/C Amys Alarm Clock/AmysAlarmClock.py | 525 | 3.90625 | 4 | def booleanConverter(boolean):
if boolean == "true":
return True
if boolean == 'false':
return False
def booleans(a,b):
if a:
if b:
return "12:00 pm"
else:
return "7:00 am"
elif b:
return "11:00 am"
else:
return "7:00 am"
# isWi... |
5a13e3ba4ada93715fafe5ca693203eace535fad | khushic/spg_codingcomp2020 | /Beginner Solutions/I Sallys Science Poster/SallysSciencePoster.py | 85 | 3.796875 | 4 | def uppercase(s1):
return s1.upper()
string1 = input()
print(uppercase(string1))
|
85c53fcebc62e08139534c06fff43dbcfdbae3fb | LaurentVeyssier/Algorithmic-problems | /problem2.py | 2,823 | 3.90625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Dec 23 02:52:52 2020
@author: lveys
"""
def rotated_array_search_sln(input_list, number, start_index, end_index):
# necessary condition to calculate the mid index
if start_index > end_index:
return -1
# Calculate mid index of the li... |
e09c18809ff42f56ab9ba3059965161c80afc19e | nmoya/coding-practice | /Algorithms/simplegraph.py | 2,172 | 4.15625 | 4 | #!/usr/bin/python
import Queue
class Graph():
def __init__(self):
self.nodes = {}
def load_graph(self, graph):
''' A python dictionary. Each key is a node with a list of edges '''
self.nodes = graph
def breadthfs(self, start):
''' Breadth First Search in the graph '''
q... |
51d22e6d7ec9ab52039057d6b0bcbb8570900e90 | nmoya/coding-practice | /Algorithms/tests.py | 9,039 | 3.625 | 4 | import unittest
import linkedlist
import stack
import queue
import queuewithstacks
import binarysearchtree
import sorting
import random
class TestLinkedList(unittest.TestCase):
def setUp(self):
self.list = linkedlist.List()
def test_list_insert(self):
for i in range(10):
self.lis... |
fbfbb4d60fa89fe2e0898eab7550332e48de5b5d | nmoya/coding-practice | /exercism/python/word-search/word_search.py | 4,672 | 3.84375 | 4 | from typing import List, Optional
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __eq__(self, other):
return self.x == other.x and self.y == other.y
def __add__(self, other):
if isinstance(other, Point):
return Point(self.x + other.x, self.y ... |
8f72ec99e56efddce1c6e71a1950a90ad6a77355 | justinli-code/python | /zonghe.py | 2,546 | 3.578125 | 4 | from math import sqrt
def car():
for x in range(1,10):
for y in range(1,10):
a=x*1100+y*11
b=int(sqrt(a))
if b*b==a:
print("撞人车辆是:陕A",a)
def zijie():
he=0
wen=open("D:\\justin\\courses for LZY.txt",encoding="utf8")#wen=open("D:\\justin\\courses for... |
4793b756d4130c2299760807d82155ca4fd8589b | justinli-code/python | /huitu.py | 356 | 3.5625 | 4 | import turtle
t=turtle.Turtle()
t.shape("turtle")
#turtle.bgcolor("black")
t.speed(10)
colors=["red"]
t.fd(-200)
for x in range(400):
t.pensize(20)
t.fd(400) #t.fd(x*3)
t.right(144) #91螺旋 170爆炸 50玫瑰 200八角星 250多瓣花 270正方 300正六边形 330近圆
t.color(colors[x%1])
t.width(x/50)
turtle.done()
|
6fc24e6d823d9d105a37fc11b640dded7694744b | redxtreme/pi_automated_scripts | /amazon_price_tracker/price_scraper.py | 734 | 3.828125 | 4 | #! /usr/bin/env python3
#This program takes an argument, the Amazon url to scrape for price
#It will return the price of the item on that page
import bs4, requests, sys
url = 'https://www.amazon.com/Timex-Unisex-TWG012800-Weekender-Leather/dp/B01GI8SU5O/'
PRICE_ELEMENT_NAME = '#priceblock_ourprice'
#If a url is passe... |
9bdfcf1304e6d4421bfb15ff2f5abb471304afc8 | KnowledgeCaptureAndDiscovery/sosen | /text_embeddings/to_array.py | 319 | 3.609375 | 4 | from argparse import ArgumentParser
parser = ArgumentParser()
parser.add_argument("file")
args = parser.parse_args()
file = args.file
with open(file, "r") as in_file:
stripped_lines = (line.rstrip('\n') for line in in_file)
lines = [line for line in stripped_lines if len(line) > 1]
print(" ".join(lines)) |
8501d3fb33cfab0c011f87904bdcbd67d337d056 | Arvinth-s/SortNebula | /shell_sort.py | 736 | 4.3125 | 4 | #This sort is similar to insertion sort, but is much faster than insertion sort.
#Here we dont compare only the adjacent element like insertion sort
def shell_sort(arr):
n = len(arr)
gap = n/2
ele=0
while(gap > 0):
for i in range(gap,n):
ele= i
while ele > gap-1 and arr[e... |
d1c01781403b49eb431f8e60ac6aef712114414b | IkumaOka/atcoder | /beginner218/a.py | 94 | 3.59375 | 4 | n = int(input())
s = input()
if s[n-1] == "o":
ans = "Yes"
else:
ans = "No"
print(ans) |
5a0cc8b3302ee9c4ece2d9f39f3ede1c888d9efc | maimaiti/dataStructureClass | /backtracking_problems.py | 6,851 | 3.5625 | 4 | from typing import List
def permute(nums: List[int]) -> List[List[int]]:
def backtrack(first = 0):
if first == n: # if all integers are used up
output.append(nums[:])
for i in range(first, n):
nums[first], nums[i] = nums[i], nums[first]
backtrack(fir... |
e068cbd2c8c17bd01b67f83c04b03fa8639264fa | bfc1557/JogoNumerosPython | /Versões antigas/JogoDoNumeroV1.1.py | 3,744 | 4.28125 | 4 | #Jogo : Adivinha o número
#Jogo feito por bfc
#Importar da biblioteca "random" o "randint"
from random import randint
#Variaveis e gerador do número
NumeroFacil = randint(1,10)
NumeroMedio = randint(1,100)
NumeroExtremo = randint(1,1000)
Tentativas = 1
Dificuldade = 0
#Inicio
print(" »»————- ★ ————-««")
print("ADIV... |
46ce25b175bc10a753ed6cc3808b05b485e89995 | Mir1135458828/python | /02dy/dengyao.py | 111 | 4.03125 | 4 | num = 10
NUM = 1
num2 = 1
while NUM<=10:
while num2<=NUM:
print(" "*num,"* "*NUM)
num2+=1
num-=1
NUM+=1
|
a4b839a01b940aec05c9fa090f42fe7cf997b80a | Mir1135458828/python | /01day/9.py | 589 | 3.75 | 4 | name = "张三"
A = "king"
pwd = "666666"
account = input("请输入账户:")
password = input("请输入密码:")
if account==A and password==pwd:
print("账户密码正确")
else :
print("密码错误!")
money = 20000#现有存款
getMoney = int(input("请输入要取款的金额:"))
if money>=getMoney:
Money = money-getMoney
print("*"*30)
print("账户:%s\n密码******\n用户姓名:%s\n原有金额:%0.... |
f33e02365cf60bf269ddf925e586df59d1160669 | Mir1135458828/python | /01day/bank.py | 1,058 | 3.75 | 4 | account = "king"
pwd = "123456"
money = 10000
b = True
while b:
Account = input("请输入账号:")
Pwd = input("请输入密码:")
if Account==account and Pwd==pwd:
print("登陆成功!")
A = 1
while A<=3:
choose = int(input("请选择功能:1.取款 2.存款 3.修改密码 4.查看余额 5.退出"))
if choose==1:
getMoney = int(input("请输入取款金额:"))
if getMoney... |
e27f6a3b8c013594f7e67bd7b1384cb0200fcd5f | iurii-kondratiuk-zz/algo-006 | /week2/week2.py | 1,220 | 3.96875 | 4 | def _Swap(arr, i, j):
temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
def _isMedian(arr, i, j, k):
return (arr[i] < arr[j] and arr[i] > arr[k]) or (arr[i] > arr[j] and arr[i] < arr[k])
def _QuickSort(arr, l, r, pivot):
global comparisons
if l >= r:
return
p = 0
if pivot == 0:
p = arr[l]
elif pivot == 2:
... |
11869749377e90b5bfad53dea8e68e224ca9c74b | zyxstudycs/Recommender-System | /Models/SimilarItemModel.py | 1,657 | 3.5 | 4 | # similar item model
# underneath it is to use a clustering model
# for simplicity, return all in the same cluster if rating is higher or equal to 3; return empty cluster otherwise
from DatabaseInterface import DatabaseInterface
from ClusteringModel import ClusteringModel
class SimilarItemModel(object):
THRESHOLD... |
0a19a4f98ba02cc13d8d89d749f30be8580fd49f | Sergey1712/TelegRun | /bullets.py | 4,415 | 3.671875 | 4 | from constants import *
import random
bullet_array = []
speed_counter = 0 # коэф. изменения скорости пули
bullet_speed = bullet_speed_init
class bullet():
def __init__(self, x, y, v_x, v_y, rad, picture):
self.x = x
self.y = y
self.v_x = v_x
self.v_y = v_y
self.rad = rad
... |
e4c86ba80903c1cb2f6f3472a7cf4d32d8d131a3 | WindSense/pyce | /pyce.py | 837 | 3.53125 | 4 | #!/usr/bin/env python2
# coding=utf-8
import sys
import json
import urllib2
def makequeryurl(word):
baseurl = 'http://dict.qq.com/dict?q='
return baseurl + word
def getpage(url):
request = urllib2.Request(url)
page = urllib2.urlopen(request)
return page
def localdict(data):
for local in data[... |
eea8b6e2a388134d007112a995d5f504c2368b4d | L200170144/prak_ASD | /02_D_144.py | 9,553 | 3.71875 | 4 | print ("============================")
print("= NAMA : AIZA FRAVY QANZA =")
print("= NIM : L200170144 =")
print("= MODUL: 2 =")
print("= KELAS: D =")
print("=============================")
from datetime import date
print ("==============================NOMER 1 =====... |
d04e0478277301342449f877f0196c81bfaa322e | 457821035/algo | /algoLeetCodePy/Leet806NumberofLines.py | 1,202 | 3.625 | 4 | '''
Created by Gavia on 2018/4/15.
'''
class Solution:
'''
Input:
widths = [4,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10]
S = "bbbcccdddaaa"
Output: [2, 4]
Explanation:
All letters except 'a' have the same length of 10, and
"bbbcccdddaa" ... |
d65cdd51fd08fe88d172aeb45afa6fff12e2c03a | msam04/Assignment4.2 | /Python_Module_4_2.py | 590 | 3.890625 | 4 |
# coding: utf-8
# In[ ]:
def len_members(list_members):
len_list = []
for mem in list_members:
len_list.append(len(mem))
return len_list
user_input = input("Please enter the list of members separated by space: ")
print("The length of the members in the input list is: ", len_members(user_input.s... |
42f6381fd8343733048f798d1aa6b9c78e57fbab | Alyas-01-08/The-towns | /work1.py | 1,132 | 3.796875 | 4 | l2 = []
l3 = []
with open('cities2.txt', 'r', encoding='utf-8-sig') as f:
l1 = f.readlines()
for i in l1:
i = i.strip().lower()
l2.append(i.strip())
while True:
a = input('Введите название города: ').lower()
if a == 'lose':
print('You are louser!!! ha ha...')
break
... |
df92149c5ca53897602e1c96515f4743822248d1 | 777shipra/Data_Structures_and_algorithms | /linked_lists/singly_linked_lists.py | 259 | 3.671875 | 4 | class Node (object):
def __init__(self,value):
self.value=value
self.nextnode=None
#how to initialise
#a=Node(1)
#how to initialise next node
#a.nextnode=b
#how to call the next node addresss
#a.nextnode
#call value
#a.nextnode.value
|
bb2b971f52e7905b461b52c757a57022b875dff0 | YogPanjarale/Statistics | /main.py | 3,392 | 3.515625 | 4 | import csv
from collections import Counter
def Weight():
print('Weight')
with open('./data/HeightWeight.csv', newline='') as f:
reader = csv.reader(f)
data = list(reader)
data.pop(0)
weightData = []
# mean
for i in range(len(data)):
_i = data[i][2]
... |
22cf9e89a2400abc4706e8333ffeb1197c3e0bfa | VetonSyn/Lottery-analyzer | /package/check_equal_numbers.py | 1,010 | 3.5625 | 4 | from collections import defaultdict
# Empty dictionary to store equal numbers
list_equal = defaultdict(list)
def check_equal():
from package.excel_reader import lottery_list
from package.variations import input_numbers_list, max_range_number, range_lottery_game_numbers
# Get the keys and values from the ... |
a806c972ccb9da634b8743904d5a599ebed8177e | Bazzaware/PythonTraining | /Exercise-00.py | 4,055 | 4.03125 | 4 | # Exercse 0
print("Hello World")
1 + 2 + 3 + 4
help(range)
x = 3.2
dir(x)
# Exercise 01
stones = 16
pounds = 10
kg = (stones * 14 + pounds) / 2.2
print(kg)
# Run to the moon
total = 0
days = 0
distance_per_day = 10
distance_to_the_moon = 238900
total_run = 0
while total_run < distance_to_the_moon:
total_run... |
2c50ef8181f608b58e442e883f9fd4ecaffc6d99 | Bazzaware/PythonTraining | /code/exercise6/location.py | 726 | 3.59375 | 4 |
class Location:
def __init__(self, name, longitude, latitude):
if not isinstance(name, str):
raise TypeError('name should be a string: {!r}'.format(name))
if not isinstance(longitude, float):
raise TypeError('longitude should be a float: {!r}'.format(longitude))
if ... |
435ea126e1d0f7623a7553d3057c3015985a5380 | SadmanTariq/TicTacToe-MiniMax | /main.py | 751 | 3.578125 | 4 | from Board import Board
import Game
import Human
import AI
CurrentBoard = Board()
player_1 = Human.Human("Human", "X")
player_2 = AI.MiniMax("Computer", "O")
while not Game.IsOver(CurrentBoard.BoardList):
CurrentBoard.PrintBoard()
CurrentBoard.BoardList = Game.UpdateBoard(CurrentBoard.BoardList, player_1)
... |
e7d11965c5709a019fb275ba48858d5e0137ce9a | Roronoazorofans/python_study | /udpsocket发送和接收数据.py | 1,090 | 3.640625 | 4 | import socket
# 判断模块是否是主模块
if __name__ == '__main__':
# 创建''udpsocket
print("123")
udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# 准备发送的数据
content = "111"
# 把数据转成二进制
# 注意:ubuntu网络调试助手是utf-8编码格式,Windows是gbk编码格式
data = content.encode("gbk")
# 发送数据
print("123")
... |
3e0c97e1cbeeeb2d9d84f1251984b5423698872b | fatalaijon/gorilla-game | /building.py | 5,570 | 3.859375 | 4 | from gamelib import GameCanvasElement
import tkinter as tk
from random import random, randint
# Probability lights are on in a room in a building
PROB_LIGHT_ON = 0.7
LIGHT_WINDOW = "yellow2"
DARK_WINDOW = "gray35"
# Min and Max building height, as a fraction of the canvas height
BLDG_MIN_HEIGHT = 0.2
BLDG_MAX_HEIGHT =... |
7dffb5324c57d7adcf50353c0644b1669b64166b | olegleyz/data-structures-and-algorithms | /merge_sort.py | 1,646 | 4.03125 | 4 | from random import randint
from random import random
from time import time
def merge_sort(arr):
# recursively divide arrays into 2 halfs and merge
if len(arr)<=1:
return arr
middle = len(arr)/2
left = arr[0:middle]
right = arr[middle:]
left = merge_sort(left)
right = merge_sort(right)
retur... |
2d722f887b90b6f2e279db0a16bb0d2a2f460607 | AndresFelipeVargas/CodeEval | /Type Ahead/main.py | 4,300 | 4.375 | 4 | '''###########################################################################
This is a program that will predict what the user will say based on the Mary
had a little lamb song. The code takes the word(s) that the user is saying and
predicts what word the user will type next. In order to use the program, the
user cr... |
e6d806fa72c615643b2027864747d41db7f818d8 | valmaci/Python | /KnapsackProblemSolutions.py | 6,668 | 3.90625 | 4 | # Course: CS2302 Data Structures
# Author: Valeria Macias
# Assignment: Lab6
# Instructor: Olac Fuentes
# T.A.: Ismael Villanueva-Miranda
# Date of Last Modification: 8/5/19
# Purpose: A Backtracking algorithm, Greedy algorithm, Randomized algorithm, and
# Dynamic algorithm implementation of the Knapsack Probl... |
cbbfc260a2626fafb614114301c93b171237047c | mihai2610/mas_labs | /lab5/agents/__init__.py | 5,313 | 3.5625 | 4 | from base import Agent
from typing import List, Dict, Any
"""
#### AGENT PARENT CLASSES
"""
class HouseOwnerAgent(Agent):
"""
Parent class for the agent that plays the role of house owner
"""
def __init__(self, role: str, budget_list: List[Dict[str, Any]]):
"""
Default constructor for H... |
942c09ded7fef7f16a7538153f1dfd117a2f1a4b | HariK77/learn-python | /inheritence.py | 581 | 3.859375 | 4 | class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
#Use the Person class to create an object, and then execute the printname method:
x = Person("John", "Doe")
x.printname()
# class Student(Person):
... |
0a1d6885f5e94f0e0174025ac86dd5dda5a4b210 | HariK77/learn-python | /data_types.py | 663 | 4.125 | 4 | # Python has the following data types built-in by default, in these categories:
# Text Type: str
# Numeric Types: int, float, complex
# Sequence Types: list, tuple, range
# Mapping Type: dict
# Set Types: set, frozenset
# Boolean Type: bool
# Binary Types: bytes, bytearray, memoryview
x = -5
y = 34.5
z = 2 + ... |
c0d636fccaed15afca7191573a1a2f860600c9b5 | HariK77/learn-python | /file-handling/file_handling.py | 281 | 3.546875 | 4 |
file = open('test.txt', 'a')
# print(file.read())
# print(file.readline())
# print(file.readline())
# for line in file:
# print(line)
file.write("\nNew Line added from the code")
file.close()
file = open('test.txt', 'r')
for line in file:
print(line)
file.close() |
70406c87bb7bfb450492c7667d768d797c1e7e44 | Kepler-XX/Codeself_py | /kepler/demo/chooice_file.py | 309 | 3.625 | 4 | import tkinter as tk
from tkinter import filedialog
'''打开选择文件夹对话框'''
root = tk.Tk()
root.withdraw()
folder_path = filedialog.askdirectory() # 获得选择好的文件夹
file_path = filedialog.askopenfilename() # 获得选择好的文件
print(f'{folder_path}')
print(f'{file_path}')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.