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 |
|---|---|---|---|---|---|---|
1d998a55804f5757a8fc98f82af63158a210093f | zhentestnice/selenium_test1 | /day1/zhucetest2.py | 865 | 3.53125 | 4 | #1.打开浏览器
from selenium import webdriver
driver = webdriver.Chrome()
#2.打开网站首页
driver.get("http://localhost/")
#3.点击注册连接
#第四种元素定位方法:链接的文本信息
driver.find_element_by_link_text("注册").click()
#driver.find_element_by_name("keyword").send_keys("zhentest")
#窗口切换:把selenium切换到新的窗口工作
cwh = driver.current_window_handle #浏览器当前窗口的... |
516e6be9f54c1246c830ceb68788c3dc25219689 | Alire-/groupMe-bots | /analysisBot.py | 11,901 | 3.71875 | 4 | import requests
import re
import sys
from pprint import pprint
# Global variable that stores the API token
at = ""
####### Interact with user for necessary parameters for analysis
# Initial menu for fetching the API token and the desired group to be analyzed
def menu():
global at
print('If you have not don... |
254ee196be76fadb0e245cb3011a65e0522e58da | Czyhandsome/game | /taosiyuan_xuexi/06_draw_100_circles.py | 873 | 3.765625 | 4 | import random
import pygame
if __name__ == '__main__':
# Create a pygame window
pygame.init()
width = 640
height = 480
screen = pygame.display.set_mode([width, height])
screen.fill([255, 255, 255])
#########################
# Actual drawing here...
#########################
fo... |
e34211288d8f4ac1f2decfd4f005167c0894d3de | Czyhandsome/game | /version1/asteroids.py | 876 | 3.671875 | 4 | import pyglet
from version1.game import resources, load
# Main game window
game_window = pyglet.window.Window(800, 600)
# Score label
score_label = pyglet.text.Label(text="Score: 0",
x=10, y=575)
# Level label
level_label = pyglet.text.Label(text="My Amazon Game",
... |
4fa906fee736ea9c758b305ef90e25dc583061c0 | Ressnn/MiniMLCore | /MiniMLCore/Losses.py | 423 | 3.640625 | 4 | from abc import ABC, abstractmethod
class Loss(ABC):
@abstractmethod
def computeLoss(expected,outputs):
return float
@abstractmethod
def computeGradients(expected,outputs):
return float
class MeanSquaredError(Loss):
def computeLoss(expected,outputs):
return (exp... |
9c3716733afa3c1798ca9a76b84f8cf20223236c | abhishekupadhyay260/google-search-using-python | /google_search.py | 271 | 3.828125 | 4 | import pywhatkit # importing the module
search_word = input("enter word or url to search \n") #to take url input from user
pywhatkit.search(search_word) # main program it will perform the Google search
print("Searching...") #not must, i printed just to look cool
|
d8a3ac3dad9c1c0629e072acffce63112aac93ad | tsaiJN/CodingInterview | /9_RecursionAndDP/9.11.py | 4,804 | 3.90625 | 4 | # Given a boolean expression consisting of the symbols 0, 1, &, | and ^, and a desired boolean result
# implement a function to count the number of ways of parenthesizing the expression such that it eval. to result
# exploit the truth table
# if we want result to be true:
# f(exp1 | exp2, true) = f(exp1, true) * f... |
bf9d7fee49b488567c0e8319f138487c0455116c | eujonas/Python | /Aula 03/questao09.py | 936 | 4.28125 | 4 | """9 - Gere as seguintes listas utilizando for e o metodo range():
Uma lista de ímpares de 10 a 12o
Uma lista pares de 2 a 1000
Uma lista de multiplos de 2 em um intervalo de decrescente de 100 até 40
Uma lista de primos de 44 até 99
OBS: Pesquise pelo método append() na documentação """
#IMPARES
impares = []
for i i... |
a2753405ecdc8a2a62423d5668d31893bd66798f | Shockn/Python | /Ajudando o Argos/prefeitura.py | 1,364 | 3.890625 | 4 | ''' A prefeitura de uma cidade resolveu fazer uma pesquisa entre os seus
trabalhadores. Para isso ela coletou alguns dados como idade, sexo (M ou F) e salario.
Crie um algoritmo que leia estes dados e que escreva ao final:
a) a media salarial dos homens, a media salarial das mulheres
b) o maior salario encontrado entre... |
1ab7e98ea5c802cb1be620bffd3286bd99408374 | EldiiarDzhunusov/COMP1001-Calculator | /mainmenu.py | 1,410 | 3.609375 | 4 | from tkinter import *
import trigonometrypage
import polynomialpage
import mathlab
def page():
# ploting the graphing
graphing = Tk()
graphing.title("Graphing")
graphing.geometry("1400x1000")
graphing.configure(background="khaki1")
heading = Label(graphing, text="Choose a type of a Graph",
... |
455a95b7fa6e88c02d7cca5655f03bd5ccc8d2ab | levitannin/PythonPossibilitiesExplored | /codeforsocialjustice/csj_ch3n4_challenge.py | 7,129 | 3.921875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Aug 22 14:33:53 2020
Following the "Coding for Social Justice" challenges by Eric Matthes.
Challenges can be found here:
https://ehmatthes.github.io/pcc_2e/challenges/coding_for_social_justice/
Chapter 3 Challenge:
Know their Names
Helping Organizations
Chapter 4... |
4f1402f21528e2145967b3c7f79f270303e948b2 | chhajed23/hwc-111-and-112 | /code.py | 6,587 | 3.5 | 4 | import pandas as pd
import statistics
import plotly.express as px
import numpy as np
import csv
import plotly.figure_factory as ff
import seaborn as sns
df=pd.read_csv("savings_data.csv")
fig=px.scatter(df,y="quant_saved",color="highschool_completed")
fig.show()
df.head()
df.highschool_completed.value_counts... |
5b519bbdb036214ef73b769fddb6f94678164cc2 | gopuu/PasswdManager | /passwdMngr.py | 6,627 | 3.75 | 4 | import sqlite3
import random
import string
import datetime
conn = sqlite3.connect('PasswdMngr.db')
c = conn.cursor()
def generatePasswd():
N = 3
str1 = random.choices(string.ascii_uppercase, k = N)
str2 = random.choices(string.ascii_lowercase, k = N)
str3 = random.choices(string.digits, k ... |
6fbff7a74b6fcfd9489b5939b089dcf5f245629d | dgellerup/laminar | /laminar/laminar_examples.py | 1,574 | 4.25 | 4 | import pandas as pd
def single_total(iterable, odd=False):
"""This example function sums the data contained in a single iterable, i.e.
a list, tuple, set, pd.Series, etc.
Args:
iterable (list, tuple, set, pd.Series, etc): Any iterable that holds data
that can be added together.
... |
3d13d6eb4f910383acc70e6ff37d519b9b6e6a5e | cam3154/NewProject | /Trial_code.py | 282 | 3.796875 | 4 | import turtle
wn = turtle.Screen()
wn.bgcolor("black")
leo = turtle.Turtle()
leo.color("red")
leo.speed(0)
def draw_picture():
for i in range(10):
for i in range(10):
leo.circle(150/(i+1),360)
leo.right(i*2)
draw_picture()
wn.exitonclick()
|
bb30179508d0a7e6e1f6d77f6ff6127acb5d27ae | vineetgupta086/Calculator | /FunKey.py | 843 | 3.90625 | 4 | def GetCoor(obj):
"""Returns the row and column of a key
Args:
obj (string): the name of the key
Returns:
int: row of
int:
"""
if isinstance(obj,int):
if obj == 0:
row, col = 5, obj
elif obj!=0:
row, col = 4 - int((obj-1)/3... |
f455cf9a565382263573f58b6dc9b8f91148663f | navarr393/a-lot-of-python-projects | /7_9.py | 490 | 3.640625 | 4 | sandwitch_orders = ['chicken', 'ham', 'pbj', 'pastrami', 'pastrami', 'pastrami']
print("Our deli has ran out of pastrami.")
finished_sandwitches = []
x = 0
while 'pastrami' in sandwitch_orders:
sandwitch_orders.remove('pastrami')
for order in sandwitch_orders:
print(f"I made your {sandwitch_order... |
6c68c7f180c0c95cc34f139f949424dec9415c88 | navarr393/a-lot-of-python-projects | /6_2.py | 164 | 3.8125 | 4 | fav_number = {'David':99, 'John':10, 'Jimmy':5, 'Alondra':35, 'Steph':12}
for number in fav_number:
print(number,"'s favorite number is:", fav_number[number]) |
f583c36b89d0b59bdd2ed5576eec4db618c5e513 | navarr393/a-lot-of-python-projects | /7_10.py | 434 | 3.875 | 4 | vacations = {}
name = input("What is your name?")
response = input("What country would your first dream vacation would be in?")
response2 = input("What is the second coutry of your dream vacation?")
vacations[name] = response
vacations[name] = response
print("\n--- Poll Results ---")
for name, response in... |
39d5bd7a475870006014f9f9ee2906ebe35c3271 | navarr393/a-lot-of-python-projects | /6_7.py | 474 | 4.125 | 4 | information = {'first_name':'David', 'last_name': 'Navarro', 'age':21, 'city':'Los Angeles'}
information2 = {'first_name':'Maria', 'last_name': 'Lopez', 'age':25, 'city':'Fullerton'}
information3 = {'first_name':'Steph', 'last_name': 'Kun', 'age':23, 'city':'Palos Verdes'}
people = [information, information2, info... |
032d07cf2e185b5c7fe2aeeda91d24d4841bde27 | navarr393/a-lot-of-python-projects | /restaurant_class.py | 433 | 3.671875 | 4 | class Restaurant:
def __init__(self, restaurant_name, couisine_type):
self.restaurant_name = restaurant_name
self.cuisine_type = couisine_type
def describe_restaurant(self):
print(f"The name of the restaurant is {self.restaurant_name}.")
print(f"The cuisine type is {s... |
d613f8996cacf3b59d3b770321c53593cf70cc79 | tylerc515/AutomateTheBoringStuff | /Chapter4/CommaCode.py | 463 | 3.828125 | 4 | def commaCode(userList):
commaSeparated = ''
if len(userList) == 0:
print('Your list is empty')
else:
for i in range(len(userList)):
if i < len(userList) - 1:
commaSeparated += userList[i] + ', '
elif i == len(userList) - 1:
commaSepara... |
964e9217dcc9578ca23e1b0bcd4fe89fa0be8193 | tylerc515/AutomateTheBoringStuff | /Chapter6/tablePrinter.py | 604 | 3.828125 | 4 | #! python3
def printTable(tableData):
colWidths = [0] * len(tableData)
for items in tableData:
for item in items:
if len(item) > colWidths[tableData.index(items)]:
colWidths[tableData.index(items)] = len(item)
for x in range(len(tableData[0])):
for y in range(... |
2891bca4ac31f275f79d41e581bbd2cac45655a4 | seemalfarooq/TestRepo | /create.py | 1,345 | 3.515625 | 4 | from selenium import webdriver
from selenium.webdriver.support.ui import Select
driver = webdriver.Firefox()
driver.get("https://www.facebook.com/")
print "Done"
driver.find_element_by_xpath("//input[@id='u_0_1']").send_keys("Rose")
print "First name found by x path and value added"
print "First name found"
driver.fin... |
cbd177c8181d7ebdcce85a1a750a50bfc0fce8f5 | jimmynguyen/rCodingHelp | /christmas-challenges/2020/day03.py | 1,255 | 3.71875 | 4 | # I wish for a white christmas... (Day 3)
# Challenge :
# Write a program that shows a snowman on the screen!
import random
import sys
import time
for i in range(5):
print(f"a snowman on the screen{('.' * i)}")
if i < 4:
sys.stdout.write("\033[F")
time.sleep(1)
# https://www.asciiart.eu/holiday-and-events/c... |
76b819b506e42b459c22d8f51657ac66d2ec4c13 | leqingxue/Python-Algorithms | /Lecture03/Homework/Homework05/020.py | 624 | 3.734375 | 4 | class Solution:
def isEqual(self, c1, c2):
if (c1 == '(' and c2 == ')'):
return True
if (c1 == '[' and c2 == ']'):
return True
if (c1 == '{' and c2 == '}'):
return True
return False
def isValid(self, s):
st = []
for character... |
b8b1134f6a2956cb31860b1d9b7eeb3ee625eb60 | leqingxue/Python-Algorithms | /Lecture02/Labs/Lab03/time3.py | 281 | 3.796875 | 4 | def BinarySearch(mylist, item):
low = 0
high = len(mylist)-1
while low <= high:
mid = (low+high)/2
if item == mylist[mid]:
return mid+1
elif item<mylist[mid]:
high=mid-1
else:
low=mid+1
return -1
|
46fc1345c99986bcdddffdbc26a207247525bbfc | leqingxue/Python-Algorithms | /Lecture01/exercises/list_test_1.py | 175 | 4.1875 | 4 | animals = ["bear", "tiger", "lion", "panda", "elephant"]
for a in animals:
print(a)
print(animals)
print(animals[-1])
print(animals[1:3])
animals[0] = "dog"
print(animals) |
0d537981ea3150b5e950022c699697af1e3b6a7c | leqingxue/Python-Algorithms | /Lecture02/Labs/Lab03/time1.py | 96 | 3.5 | 4 | n = 100
for i in range(n):
if i % 2 == 0:
print(i//2)
else:
print(i**2) |
f47e7f8c85bfc4060198e04a53183b9a76074f8f | leqingxue/Python-Algorithms | /Lecture07/Homework/Homework02/get_n_expensive_cheap_items_solution.py | 558 | 3.53125 | 4 | import heapq
from pprint import pprint
items = [
{'name': 'Item-1', 'price': 101.1},
{'name': 'Item-2', 'price': 555.22},
{'name': 'Item-3', 'price': 45.09},
{'name': 'Item-4', 'price': 22.75},
{'name': 'Item-5', 'price': 16.30},
{'name': 'Item-6', 'price': 110.65}
]
cheap = heapq.nsmallest(3,... |
7536ea6c87079d6127796a416446ae65950325a1 | leqingxue/Python-Algorithms | /Labs/Lab1_09.py | 351 | 3.984375 | 4 | a = {
'x': 1,
'y': 2,
'z': 3
}
b = {
'w': 10,
'x': 11,
'y': 2
}
# Find keys in common
result = a.keys() & b.keys() # { 'x', 'y' }
print(result)
# Find keys in a that are not in b
result = a.keys() - b.keys() # { 'z' }
print(result)
# Find (key,value) pairs in common
result = a.items() & b.items... |
6b2e7b7d1544d67e8a867a2316cb045a015006a2 | leqingxue/Python-Algorithms | /Lecture07/Exercises/find_pair.py | 690 | 4.03125 | 4 | # https://www.techiedelight.com/find-pair-with-given-sum-array/
# Naive method to find a pair in a list with the given sum
def findPair(A, sum):
# consider each element except the last
for i in range(len(A) - 1):
# start from the i'th element until the last element
for j in range(i... |
4a4127a94f0b510000be3724caa6f204ac602025 | leqingxue/Python-Algorithms | /Lecture01/Labs/Lab01/rec_cum_solution.py | 715 | 4.125 | 4 | # Write a recursive function which takes an integer and computes the cumulative sum of 0 to that integer
# For example, if n=4 , return 4+3+2+1+0, which is 10.
# This problem is very similar to the factorial problem presented during the introduction to recursion.
# Remember, always think of what the base case will loo... |
697d340763b3e95d0ce27a78657791bbc9d52ca4 | leqingxue/Python-Algorithms | /Lecture02/exercises/bigo_worst_best.py | 316 | 3.78125 | 4 | def matcher(list, match):
# Given a list, return a boolean
# indicating if match item is in the list
for item in list:
if item == match:
return True
return False
########################################
lst = [1,2,3,4,5,6,7,8,9,10]
print(matcher(lst,1))
print(matcher(lst,11)) |
e85e8d663620159963eae7299c4677d17e628772 | leqingxue/Python-Algorithms | /Lecture07/Exercises/heap_v5.py | 170 | 3.515625 | 4 | import heapq
h = [21, 1, 45, 78, 3, 5]
print(h)
# Use heapify to rearrange the elements
heapq.heapify(h)
print(h)
# Repalce an element
heapq.heapreplace(h, 6)
print(h) |
06fdfc119cb192d56994633cff8bb8bca6aafff6 | leqingxue/Python-Algorithms | /Lecture06/Homework/Homework02/delete_node_solution.py | 1,790 | 4.0625 | 4 | # Definition: Binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def delete_Node(root, key):
# if root doesn't exist, just return it
if not root:
return root
# Find the node in the left subtree if key valu... |
b6b6bbc1dec2811f31f152bdb7bc579675b0d20d | scorourk/PBD_SOR | /CA_3/DBS_Hire_Car_User.py | 3,885 | 3.953125 | 4 | #CA 3 Programming for Big data. B8IT105 (B8IT105_1617_TMD3)
#Stuart O'Rourke
#Student Number: 10334192
#DBS Car Rental.
from car import * # import all instances of the car class
class Dealership(object):
def __init__(self):
self.electric_cars = []
self.petrol_cars = []
self.diesel_cars = []
self.hybrid_c... |
2a3d2d00ccba81a596ec9e9b6296c115ac1b583a | woshiZS/Snake-Python-tutorial- | /Chapter3/cube.py | 336 | 4.40625 | 4 | cubes=[value for value in range(1,11)]
for cube in cubes:
print(cube)
print("The first 3 items in the list are : ")
for num in cubes[:3]:
print(num)
print("Three items from the middle of the list are : ")
for num in cubes[4:7]:
print(num)
print("The last 3 items in the list are : ")
for num in cubes[-3:]... |
6a3bf017f39aaa96ed6804a363d281f0a630eceb | woshiZS/Snake-Python-tutorial- | /Chapter4/alienColor.py | 190 | 3.90625 | 4 | color='red'
if color=='green':
print("You have earned 5 points!")
elif color=='yellow':
print("You have earned 10 points!")
elif color=='red':
print("You have earned 15 points!") |
f6d86abaa5ddfb5d4ac0da841c2b9387a143b3b9 | woshiZS/Snake-Python-tutorial- | /Chapter7/test.py | 118 | 3.71875 | 4 | def change(nums):
for i in range(len(nums)):
nums[i]+=1
temp=[1,2,3,4,5,6,7,8,9]
change(temp)
print(temp) |
c9bdc3416fd4332929d1938a57f58eb4fd75bcf5 | woshiZS/Snake-Python-tutorial- | /Chapter4/conditionTest.py | 453 | 4.09375 | 4 | target='MoneyMoneyMoney'
if not target=='Happy':
print("You've lost the game!")
a,b=3,4
if not a==b:
print("a do not equal to b!")
sequence=['char','int','long','boolean']
if 'double' not in sequence:
print("Double is not included!")
if 'char' in sequence:
print("Char is included!")
if 'Char'.lower()... |
f8c34f7c0e7c330eb127ae61ecd3d0382c8bab59 | woshiZS/Snake-Python-tutorial- | /Chapter4/favoriteFruits.py | 374 | 3.84375 | 4 | favoFruits=['apple','banana','pear','peach','watermelon']
if 'grape' in favoFruits:
print("I really love grapes!")
if 'apple' in favoFruits:
print("I really love apples!")
if 'cucumber' in favoFruits:
print("I really love cucumber!")
if 'watermelon' in favoFruits:
print("I really love watermelon!")
if ... |
d7bef5ad78d046a24a627e3190a4102f658d23c3 | louismcs/hansard-sentiment | /src/dates.py | 413 | 3.515625 | 4 | """ Contains code related to dates """
from datetime import date
from datetime import timedelta
DB_PATH = 'Data/corpus.db'
START_DATE = date(2001, 9, 11)
END_DATE = date(2003, 3, 19)
def date_range(start_date, end_date):
"""Returns all dates between start_date (inclusive) and end_date (exclusive)"""
for co... |
13c9170deadd56cf6ce78877debdbb135c30408e | anguloag/Python-Challenge | /PyPoll/main.py | 5,580 | 4.03125 | 4 | # Script must analyse election_data.csv and calculate the following:
#--- Total number of votes cast
#--- A complete list of the candidates who received votes
#--- Percentage of votes each candidate won
#--- Total number of votes each candidate won
#--- Winner of the election based on popular vote
# Script must also pr... |
cce428e8f38469ed850384e77f285505247ef30b | jcalven/hotels-scraper | /hotscrape/parser.py | 3,402 | 3.546875 | 4 | import pandas as pd
import re
def parse_price(row, sale=False):
"""
Extract price data from `price`column
"""
row = row[1]["price"]
# Extract dollar amounts from string
row = re.findall(r"\$\d+", row)
if not row:
return None
elif len(row) == 1:
if sale:
retu... |
72d160020397748867603e168097ecfc88b82077 | andres925922/Python-Design-Patterns | /src/3_examples/Creational/abstract_factory.py | 2,672 | 3.6875 | 4 | # -----------------------------------------------------------------------------------------------------------------
# Abstract Factory example: Web and intranet are two different applications. Both use Sql And No SQL databases,
# Web uses mongodb and SQL but intranet uses Oracle and OrientDB. Both have different imple... |
0d8a2dea4bdafa61851e58509bbf5adc04022818 | andres925922/Python-Design-Patterns | /src/3_examples/Structural/adapter.py | 829 | 4.125 | 4 | """
Convert the interface of a class into another interface clients expect.
Adapter lets classes work together that couldn't otherwise because of
incompatible interfaces.
"""
from abc import ABC, abstractmethod
# ----------------
# Target Interface
# ----------------
class Target(ABC):
"""
Interface for C... |
b80dbda1bdcc6b4cb53ce456306fb6599f21c7b3 | anukrit01/Matplotlib-Package | /matplot_types.py | 654 | 3.515625 | 4 | import matplotlib.pyplot as plt
import numpy as np
'''
#Plotting Histogram
y = np.random.randn(100,100) #100 X 100 array of a guassian distribution
plt.hist(y)
plt.show()
#Plotting a Dict. using Bar Chart
d = {'a':25, 'b':45, 'c':52}
for i, key in enumerate(d):
plt.bar(i, d[key])
plt.xticks(np... |
4fc0cc63a97da7988e3a1a682ffbb2e323e249ac | TrentEhrhart/HENTFT | /newuserprediction.py | 3,087 | 3.671875 | 4 | def new_user_prediction():
# This function outputs predictions for next menses date, ovulation date, and fertile window if the user has been on the app for less than 90 days
import pandas as pd
import datetime
#loading in test dataset from excel: Real data would come into the backend via a .csv fi... |
0007b8cc944994bd152ac2562cdc9c12d335d05e | mo-mosverkstad/abstract_file_operation | /all_abstraction/libs/libscore.py | 3,807 | 3.65625 | 4 | #!/usr/bin/env python
from msvcrt import getch
import os
password = '1687621156'
def sleep_infintity_seconds():
while True:
pass
def sys_password():
print('Please enter password to go in to Mos system')
for i in range(3):
if input('Please enter the password here >>>') == password:
... |
e3f2f98232600e99b76986f63d105fe319535563 | ruiwanbing/travelratings | /get_wb_indicator_by_country.py | 834 | 3.640625 | 4 | import wbdata
import datetime
import pandas as pd
import numpy as np
def get_latest_wb_indicator_by_country(name: str, indicator: str):
# Get raw data
date = (datetime.datetime(2016, 1, 1), datetime.datetime(2016, 1, 1)) # hwo to automatically select latest date?
raw_data = wbdata.get_data(indicator=indi... |
d63b47cc028440f91de93b4f2afe0e729bda88fd | Environmental-Informatics/building-more-complex-programs-with-python-Gautam6-asmita | /Second_attempt_Exercise5.2.py | 1,180 | 4.53125 | 5 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Created on 2020-01-24 by Asmita Gautam
Assignment 01: Python - Learning the Basics
Think Python Chapter 5: Exercises 5.2
##Check fermat equation
Modified for resubmission on 2020-03-04
"""
"""
This function 'check_fermat' takes 4 parameters: a,b,c and d
to check th... |
a30bf3b9a69fd8c038a34801dc6feb82e5260c5a | PabloJoel/mcts | /players/BTree.py | 1,057 | 3.90625 | 4 |
class BTree():
#Bidirectional Tree
def __init__(self, game, parent, value=0, visits=0, nodes=None):
"""Tree for Monte Carlo Tree Search.
-Game is the move that is being analyzed
-Parent is the parent of the node
-Value is value of the node
... |
17475f3697b6efd0dc8780bb8966b880a04b1397 | codecherry12/Data_Structues_AND_Algorithms | /TREES/General Tree.py | 1,513 | 3.546875 | 4 | '''
Electronics
|__Laptop
|__Mac
|__Surface
|__Thinkpad
|__Cell Phone
|__Iphone
|__Google Pixel
|__Vivo
|__TV
|__Samsung
|__LG
'''
class TreeNode:
def __init__(self,data):
self.data=data
self.children=[]
self.parent=None
def add_ch... |
58989bb50deea9a60c971bcc350f648a580a7d34 | codecherry12/Data_Structues_AND_Algorithms | /Queues/Queue.py | 882 | 3.90625 | 4 | class queuelist:
def __init__(self):
self.data=[]
def isempty(self):
return len(self.data)==0
def __len__(self):
return len(self.data)
def enque(self,ele):
self.data.append(ele)
def display(self):
if self.isempty():
print("queue is empty")
... |
3ba88a0c29f0e2273c55cbed8b5f7fd9aa27254d | Draft00/TCMK | /HelloWorldTest/HelloWorldTest/HelloWorldTest.py | 243 | 3.8125 | 4 | def gcd_rem_division(num1, num2):
while num1 != 0 and num2 != 0:
if num1 >= num2:
num1 %= num2
else:
num2 %= num1
print (num1 or num2)
gcd_rem_division(168, 105)
# print(a) # Выведет 21
|
893debc38b67568f99a6e66f6f6443a329e20c3b | lvbohaiou/ZYC-Project | /2017-12-16.py | 183 | 3.609375 | 4 | import time
import os
a = 1
b = 2
if a > b:
print("a is bigger")
else:
print("b is bigger")
print("我就是要修改")
print("这里是可以的")
print("又被修改了")
|
d5dedd27469814b0ce306d8c68cc6009163ef2c1 | reizhu/TwitterScraping | /twitterTest.py | 1,878 | 3.609375 | 4 | import GetOldTweets3 as got
from datetime import date
import time
# The word to search for
word = 'mcdonald'
# The file to write to
f = open("usernameTest.txt", "a")
# today's date
today = date.today()
# today's date as a string
since = today.strftime("%Y-%m-%d")
# The script will go until stopped
functio... |
6d9f05b63b030a7e5a351749468067d9deec27a5 | edrogers/GeometryPuzzle | /drawCircles.py | 2,217 | 3.5 | 4 | #!/usr/bin/python
import Image, ImageDraw, ImageFont
import sys
from math import pi, cos, sin, radians, sqrt
alphaDeg=float(sys.argv[1])
alpha=radians(alphaDeg)
circleAcentX=0
circleAcentY=0
circleAradius=200
pointAX=circleAcentX-circleAradius
pointAY=circleAcentY
pointBX=circleAcentX-circleAradius*cos(alpha)
poin... |
874ccbb595cae3e88462677f547e537b22a7a30c | aminhp93/python_fundamental | /multiply.py | 218 | 4.03125 | 4 | # def multiply_by_five(arr):
# i = 0
# while i < len(arr):
# arr[i] = arr[i] * 5
# i += 1
# return arr
# print multiply_by_five([1,2,3])
arr = [1,2,3]
for i in arr:
if(i==1):
i = 'test'
# print i
print arr |
7c25fcce7da65e506b5bdff9b8e5a0f69714c4fd | imooncoco/Keras | /keras08_R2.py | 1,627 | 3.609375 | 4 | #1. 데이터
import numpy as np
x = np.array(range(1, 101))
y = np.array(range(1, 101))
print(x.shape)
print(y.shape)
from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test, = train_test_split(x, y, train_size = 0.6, random_state=66, shuffle=False)
x_val, x_test, y_val, y_test, = train_test... |
ea3a06ac165152baade99a551f6fe2d7740ba635 | mrsleveto/PythonProgrammingAssignmentSolutions | /Conversation with a computer.py | 743 | 4.1875 | 4 | #Conversation with a computer, by: Mrs. Leveto
doing_well=input("Hello, are you doing well today? (y/n): ")
if doing_well == "y" or doing_well == "Y":
print("Wonderful! I'm so glad!")
reason=input("What has you in such a great mood today? (weather/school/friends): ")
if reason == "weather":
print("... |
976e91fb1893930dd0f07aace31d5b6625d422bf | manoj-abhisargahas/BlackJack | /BlackJack.py | 5,028 | 3.75 | 4 | from random import shuffle, choice, randint
print ":::::::::::::::::::::::::::::::::::::::"
print ":::::::::::::: BLACKJACK ::::::::::::::"
print ":::::::::::::::::::::::::::::::::::::::"
def sysassign(turn):
yurcards.append(cards.pop(randint(0,len(cards)-1)))
print "\nSystem assigns card-%d to you:"%... |
dd5d716d9ab620aefb37ed05c2dff7949eb32cc2 | cricklet/Hatched | /scripts/calculate fps/sum.py | 124 | 3.75 | 4 | total = 0
num = 0
for line in file('numbers.txt'):
total += float(line)
num += 1
avg = total / num
print 1 / avg
|
4a39f670a8d8bacedc133c8dfafde5519f4c8dac | karim-aboelazm/Machine-Learning-A-Z-Hands-On-Python | /02.Regression/3.Polynomial Regression/polynomialRegression.py | 1,181 | 3.890625 | 4 | # Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('Position_Salaries.csv')
X = dataset.iloc[:, 1:2].values
y = dataset.iloc[:, -1].values
# Performing Linear Regresion
from sklearn.linear_model import LinearRegression
lin_reg... |
a5b863ee6a597f0a28f3aabcdbdea59505b55d21 | learner-d/IAD_Labs | /Lab5/LeastSquares.py | 367 | 3.515625 | 4 | import numpy
import math
from Constants import N, X, Y
#Возвращает коэфициенты m, c
def calculate():
sumX = X.sum()
sumY = Y.sum()
sumXY = (X*Y).sum()
sumXX = (X*X).sum()
#Вычислить m
m = (N*sumXY - sumX*sumY) / (N*sumXX - sumX**2)
#Вычислить c
c = (sumY - m*sumX) / N
ret... |
a54de8e95ad55aea57cdba22dfde49aba7be1659 | moussazeghida/code.kx.com | /contrib/serpent.speak/trunk/K/Lib/K.py | 8,788 | 3.875 | 4 | """access k from python
>>> x = k("1 2 3 4 5")
>>> x.asarray()
array([1, 2, 3, 4, 5])
"""
from pyk._k20 import \
_K, \
_gi, _gf, _gc, _gs, _gn, _gp, _gk, _ksk, \
_Ki, _Kf, _Kc, _Ks, kerr
from pyk._nk20 import \
_ktoarray, _arraytok
import Numeric
__version__ = '$Revision: 1.4 $'
class K(_K):
... |
4cf5bca709b694c3c550a764f15f637f835348ba | altruistcoder/hacktoberfest-19 | /Miscellaneous/largest_contiguous_array_sum.py | 668 | 4.03125 | 4 | from sys import maxsize
# Function to find the contiguous subarray whose sum is maximum in the array and also print this subarray
def maxSumSubarray(a, n):
max_total = -maxsize - 1
max_curr = 0
start = 0
end = 0
s = 0
for i in range(0, n):
max_curr += a[i]
if max_total < max_cur... |
16f66bb9ffe31d208e605302ec3dae720a2348b2 | jabadia/advent-of-code-2017 | /d3/d3p2.py | 1,716 | 3.5625 | 4 | from collections import namedtuple
TestCase = namedtuple('TestCase', 'case answer')
TEST_CASES = [
TestCase(1, 0),
TestCase(2, 1),
TestCase(3, 2),
TestCase(4, 4),
TestCase(5, 5),
TestCase(10, 26),
]
def check(case, actual):
if case.answer != actual:
print("bad answer for case %d:... |
14466fd54bdb42f70a0f2535cd08ac745302e711 | Kamilgeek/client_server_home | /class_work/lesson_2/class_2.py | 1,030 | 3.6875 | 4 | # file = open('data/read.txt')
# print(file.read())
# print(file.readline())
# print(file.readlines(16))
# print(file.readlines(32))
# print(file.readlines(64))
# with open('data/read.txt') as file:
# for row in file:
# print(row)
# with open('data/write.txt', 'w') as file:
# pass
# with open('data/wr... |
628e0e7109416a6416c9b9684c687042d455b801 | zhwork92d/datastructrue | /bubblesort/bubble_sort.py | 598 | 3.734375 | 4 | # coding:utf-8
"""
.pyļʵð
"""
def bubble_sort(lst):
"""
ðpythonʵ
"""
for i in range(len(lst)):#i07
flag=True;#ñflagǷѾ
for j in range(1,len(lst)-i):#j1len(lst)-i
if lst[j-1]>lst[j]:
lst[j-1],lst[j]=lst[j],lst[j-1]
flag=False
... |
a4134eb61c9d56b6c11d4d993c18b72f92e9fdf3 | FilipDuz/CodeEval | /Moderate/ARRAY_ABSURDITY.py | 1,495 | 4.125 | 4 | #ARRAY ABSURDITY
"""
Imagine we have an immutable array of size N which we know to be filled with integers ranging from 0 to N-2, inclusive. Suppose we know that the array contains exactly one duplicated entry and that duplicate appears exactly twice. Find the duplicated entry. (For bonus points, ensure your solut... |
4e909840e28b83309a8be951991510fe230525db | FilipDuz/CodeEval | /Hard/STRING_PERMUTATIONS.py | 3,779 | 4.59375 | 5 | #STRING PERMUTATIONS
"""
Write a program which prints all the permutations of a string in alphabetical order.
We consider that digits < upper case letters < lower case letters. The sorting should be
performed in ascending order.
"""
"""
PROGRAM EXPLANATION:
This program prints permutations of a string in alphabeti... |
6bfa52dee997242f6766a53220a504e8a8e591f0 | FilipDuz/CodeEval | /Easy/ODD_NUMBERS.py | 118 | 3.515625 | 4 | #Print the odd numbers from 1 to 99.
numbers=[x for x in range(1,100)]
odds=numbers[::2]
for x in odds:
print x
|
5a82cacd4bf322b1200c0f66f89e5a9d950856f9 | FilipDuz/CodeEval | /Moderate/REMOVE_CHARACTERS.py | 1,393 | 4.34375 | 4 | #REMOVE CHARACTERS
"""
Write a program which removes specific characters from a string.
INPUT SAMPLE:
The first argument is a path to a file. The file contains the source strings and the characters that need to be scrubbed. Each source string and characters you need to scrub are delimited by ... |
936915f8b706f99df7a5be63e7c61df03dac0868 | Gustavo-Gil/Python-Marathon | /lesson01.py | 4,147 | 4.46875 | 4 | # Declare abaixo uma variável chamada year
# e atribua a ela o ano em que Python foi criado (tipo int).
year = 1992
# Declare abaixo uma variável chamada third_principle e
# atribua a ela a 3ª linha do "Zen of Python" (tipo string).
third_principle = "Simple is better than complex."
# Declare abaixo uma variável ch... |
14662462fa0e3906e3fa9aca4e7ceef296a317dd | 1770537101/strroe | /数字游戏.py | 1,570 | 3.796875 | 4 | '''
猜数字游戏:
1.系统随机产生一个随机数字(0~1000)
2.用户从键盘输入数字,与随机数字进行比对 (让用户循环输入20)
若大了:温馨提示,大了
若小了:温馨提示,小了
猜中
3.循环:一直到猜中为止,退出程序。
技术分析:
1.随机数
random
2.input
3.判断
if ...elif ...else
4.循环
while : 当型循环条件型循环
5.退出... |
3c3be9631a8e55918ea37672e5223a56b3b2f5a2 | tianlinhe/capstone_project_immigration | /funcs.py | 4,163 | 3.75 | 4 | import seaborn as sns
from pyspark.sql.functions import isnan, when, col, count
def show_nan_pd(df):
"""Given a pandas df, visualize the %nan in each column
:param df: pandas dataframe
:return:
"""
# count % nan in each column
dfnull=df.isnull().sum()/len(df)*100
# show only columns contai... |
2d6b08cbeeeffd4e19d4afeb106bb0636c31cd89 | ragu6963/kfq_python_machine_learning | /scikit_learn/3_Classifier/1_Decision_Tree/2_scikit_overfitting.py | 2,040 | 3.625 | 4 | """
결정트리 과적합
과적합 문제 시각화
"""
# %%
from sklearn.datasets import make_classification
import matplotlib.pyplot as plt
# %%
plt.title("3 Class values with 2 Features Sample dat a creation")
x_features, y_labels = make_classification(
n_features=2,
n_redundant=0,
n_informative=2,
n_classes=3,
n_cluster... |
00c103d71c554cfd06a7e570088f11409ebfd006 | gsevtlana/epi_book_python | /ch_13_1.py | 1,597 | 3.8125 | 4 | # -*- coding: utf-8 -*-
"""
# -----------------------------------------------------------------------------
# Copyright (c) 2015, Laurent George.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-------------------------------... |
a1706b4d138c744bb60d6a4a3bc1ddffbb0ad52d | gsevtlana/epi_book_python | /ch_17_5.py | 1,632 | 3.671875 | 4 |
def search_for_sequence(S, A):
"""
WARNING it does works only if number in A are unique, if there are multiple path in A (i.e same number multiple time) this does not work.
:param S:
:param A:
:return:
ok for complexity:
building neighbors table = O(n*m*4)
then looping over S = O(len... |
40b44c273b8848d082e06e365b181eb80ddbafde | gsevtlana/epi_book_python | /ch_17_1.py | 1,473 | 3.734375 | 4 |
def count_score_combination(W, score):
"""
Exponential complexity
:return:
>>> count_score_combination([], 10)
0
>>> count_score_combination([1], 10)
1
>>> count_score_combination([1, 2], 3)
2
>>> count_score_combination([2, 3, 7], 12)
4
"""
count = 0
if not(W)... |
e24ab5a5057c8784db5dda6d8c7f8ac46d515ff5 | jackiekazil/data-wrangling | /code/chp8-cleanup/our_first_script_with_main_and_functions.py | 982 | 3.6875 | 4 | """ This section goes at the bottom of the script we've already written. """
def main():
data_rows = get_rows('data/unicef/mn.csv')
header_rows = get_rows('data/unicef/mn_headers_updated.csv')
skip_index, final_header_rows = eliminate_mismatches(header_rows,
... |
97c9644b95349651b0671a2e3de5f5f6342619b5 | jackiekazil/data-wrangling | /code/chp8-cleanup/our_cleanup_script.py | 7,423 | 3.71875 | 4 | """
Usage: python our_cleanup_script.py
This script is used to intake the male survey data from UNICEF
and save it to a simple database file after it has been checked
for duplicates and missing data and after the headers have been properly
matched with the data. It expects there to be a 'mn.csv' file with the
data and... |
3bcfab19e50d4d2e84ef69b7f1e25ac481a9309f | uc-mitchbr/it3038c-scripts | /final/routes.py | 1,587 | 3.90625 | 4 | from flask import Flask, render_template, request
#using the flask app to create a web server
app = Flask(__name__)
app.config.from_object(__name__)
@app.route('/')
def hello():
return render_template("index.html")
@app.route('/welcome', methods=['GET', 'POST'])
def welcome():
if request.method == "POST":
... |
289ad787090b4a6c692fc2088213b73171add2a5 | sonalpawar2196/PythonTrainingDecember | /List/ListDemo.py | 1,637 | 4.4375 | 4 |
thisList = ['sonal','priya','abc','pqr']
print(thisList)
print(thisList[1])
thisList[1] = "jjj"
print(thisList)
# iterating over list
for x in thisList:
print(x)
if "sonal" in thisList:
print("string is in the list")
else:
print("not present ")
print("length of list = ",len(thisList))
#To add an it... |
94ecb87eaff143a8c293d17189563cd0559f81ca | fedemonte95/MatrixCalculator | /OperacionesMatrices.py | 3,343 | 3.953125 | 4 |
# Programa para multiplicar matrices
## Diagrama de entradas, sálidas y limitaciones
##
## m1 m2
## | |
## v v
## __ __ __ __ __ __ __ __
## | |
## | multiplicación | limitacion : valores de m1 y m2 debe... |
525fa2c6b200496b8c9a5a748127f5e4f60a6819 | swapnilz30/python | /create-file.py | 734 | 4.4375 | 4 | #!/usr/bin/python3.6
# This script create the file.
import os
from sys import exit
def check_file_dir(file_name):
# Check user enter value is dir or file.
if os.path.isdir(file_name):
print("The ", file_name, "is directory")
exit()
elif os.path.isfile(file_name):
print("The ", fi... |
5782c0fd39184b1f3ea57b5e87eb92c86a040467 | swapnilz30/python | /file-write-while-true.py | 1,642 | 3.921875 | 4 | #!/usr/bin/python3.6
# This script writes the continuous to the file.
# This script is ready but need to handle the keyboard interrupt
import os
from sys import exit
# Check the input object is dir or file.
def check_input(ifile):
global file_status
if os.path.isdir(ifile):
print("The ", ifile, "is ... |
ae5b8a2b0c7300cf54a7c7cfbe6a843300ea09e3 | reach-the-sky/Python-Main-GUI | /Framework_for_auto_mail.py | 2,720 | 3.53125 | 4 | from tkinter import *
from tkinter import messagebox
from tkinter import ttk
import smtplib
root = Tk()
root.title("Email Details")
Email_Sent_Number = 0
Username_Label = Label(root,text = "Email Id: ")
Username_Label.grid(row=2,column=1)
Username_Entry = ttk.Entry(root,width = 50)
Username_Entry.grid(row=2,c... |
18f419b24691e1d57ba3479c244709cbc751edc5 | MayLSantos/Atividade-de-Revis-o | /QUESTAO 5 - (B).py | 634 | 3.78125 | 4 | class Stack():
def __init__(self):
self.lista = []
def push (self, valor):
self.lista.append (valor)
def pop (self):
if (not(self.isEmpty())):
return self.lista.pop()
def isEmpty(self):
return len(self.lista) == 0
def length (self):
retu... |
55821ffc60ba82eb63613088dca01fe92cb84171 | EthanPrentice/GetTextFromFileTypes | /main.py | 2,456 | 3.578125 | 4 | '''
Created on 4 Apr 2017
@author: Ethan
'''
import os
import glob
directoryInput=""
directoryOutput=""
#Gets the input directory for getting files
def getDirectoryInput():
global directoryInput
directoryInput = raw_input("Enter directory to scan: ")
try:
#tests if input directory is real
... |
6f84b439cc1b1a3b547281c6ef9d05a2c6cd6145 | Shubhu0500/Shubhu0500 | /ROCK_PAPER_SCISSORS.py | 1,072 | 4.28125 | 4 | rock = '''
_______
---' ____)
(_____)
(_____)
(____)
---.__(___)
'''
paper = '''
_______
---' ____)____
______)
_______)
_______)
---.__________)
'''
scissors = '''
_______
---' ____)____
______)
__________)
(____)
---.__(___)
'''... |
5c9737e34a7ce2f1b06a5f07f282d4f0d2fb17e7 | webis-de/small-text | /small_text/training/metrics.py | 754 | 3.6875 | 4 | class Metric(object):
"""Represents an arbitrary metric.
"""
def __init__(self, name, dtype=float, lower_is_better=True):
"""
Parameters
----------
name : str
A name for the metric.
dtype : any type, default=float
Data type of the metric.
... |
5895b5731eb6c7ba87a255eb63949f97db41eb44 | kunalJa/leetcodeforces-etc | /LeetCode/easy/937_reorder_data_in_log_files.py | 3,782 | 3.984375 | 4 | """
https://leetcode.com/problems/reorder-data-in-log-files/
You have an array of logs. Each log is a space delimited string of words.
For each log, the first word in each log is an alphanumeric identifier. Then, either:
Each word after the identifier will consist only of lowercase letters, or;
Each word a... |
2c6c40847ef4419d0c74e6f8d56bdcfdef9cefc4 | kunalJa/leetcodeforces-etc | /LeetCode/medium/958_check_completeness_of_a_binary_tree.py | 1,992 | 4.03125 | 4 | """
https://leetcode.com/problems/check-completeness-of-a-binary-tree/
Given a binary tree, determine if it is a complete binary tree.
In a complete binary tree every level, except possibly the last, is completely filled,
and all nodes in the last level are as far left as possible.
It can have between 1 and 2h nodes ... |
06e1ca74f0a29f19f2fa08b84ab6ecf560b1e26e | kunalJa/leetcodeforces-etc | /LeetCode/hard/123_best_time_to_buy_and_sell_3.py | 2,220 | 3.890625 | 4 | """
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete at most two transactions.
Note: You may not engage in multiple transactions at the same time
... |
5617e3e22546b94616238fe66cf94fa2929ba996 | kunalJa/leetcodeforces-etc | /LeetCode/medium/701_insert_into_a_binary_search_tree.py | 1,545 | 3.953125 | 4 | """
https://leetcode.com/problems/insert-into-a-binary-search-tree/
Given the root node of a binary search tree (BST) and a value to be inserted into the tree,
insert the value into the BST. Return the root node of the BST after the insertion.
It is guaranteed that the new value does not exist in the original BST.
No... |
8e0dcc88389586a9a0a13491e020ea9730eff66d | kunalJa/leetcodeforces-etc | /Codeforces/977/977A_wrong_subtraction.py | 1,137 | 3.6875 | 4 | """
https://codeforces.com/problemset/problem/977/A
Little girl Tanya is learning how to decrease a number by one, but she does it wrong
with a number consisting of two or more digits. Tanya subtracts one from a number by the
following algorithm:
if the last digit of the number is non-zero, she decreases the numbe... |
bbe6a5a04e6eb37862c688b5835cde6cee942e9f | kunalJa/leetcodeforces-etc | /LeetCode/challenge/may2020/9_valid_perfect_square.py | 686 | 3.75 | 4 | """
https://leetcode.com/explore/challenge/card/may-leetcoding-challenge/535/week-2-may-8th-may-14th/3324/
Given a positive integer, write a function which returns True if num is a perfect square else False.
Do not use any built-in library function such as sqrt.
"""
"""
Accepted:
Time complexity: O(n) where n^2 is t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.